Compare commits

..
31 Commits
Author SHA1 Message Date
seven332 9590c758fd 1.0.9 2016-05-03 02:50:51 +08:00
seven332 74bbbabdd4 Add debug print Image count 2016-05-03 02:46:24 +08:00
seven332 363ad7686e Use ImageMovableTextTexture instead of MovableTextTexture
NativeTexture can avoid bad buffer
2016-05-03 02:34:23 +08:00
seven332 ad9f544fe1 Add GLView.onPause and GLView.onResume 2016-05-03 00:52:03 +08:00
seven332 4c3c84f1a6 Clean up 2016-05-02 23:17:29 +08:00
seven332 512fef80db Bump TuXiang library version to 0.1.1 2016-05-02 22:50:36 +08:00
seven332 fad9e3ccc0 1.0.8 2016-05-02 19:38:21 +08:00
seven332 5aa56e0237 Add detail size options
Large for 480dp width
Small for 320dp width
2016-05-02 19:36:41 +08:00
seven332 d4d4ba8c75 Use TuXiang library
Make GLRootView extends com.hippo.tuxiang.GLSurfaceView
2016-05-02 18:56:56 +08:00
seven332 2a324c4d89 Call GLRootView onPause and onResume 2016-05-02 13:20:35 +08:00
seven332 e6638b6f56 Remove ANRWatchDog 2016-05-01 23:20:00 +08:00
seven332 5d956b43fb 1.0.7 2016-05-01 17:11:17 +08:00
seven332 9e19b16735 Close #142, save thumb to download dir 2016-05-01 17:08:03 +08:00
seven332 af8cc34048 Bump image library version 2016-05-01 15:53:18 +08:00
seven332 430e748490 Remove TODO list 2016-05-01 15:23:46 +08:00
seven332 297c35b14d Use custom GLSurfaceView
Ensure GLRootView's mContentView.detachFromRoot() called in render thread
2016-05-01 15:21:26 +08:00
seven332 b973e0244e Add gallery image cache 2016-05-01 13:26:13 +08:00
seven332 f672fe1e96 Remove 'git submodule update --init' in build instruction 2016-04-30 19:09:22 +08:00
seven332 e3113083bc Use jitpack libraries 2016-04-30 19:03:59 +08:00
seven332 d186a6ac3b Run copyNotice task automatically 2016-04-28 02:07:17 +08:00
seven332 10693c5ffc Use jack and jill 2016-04-27 22:07:42 +08:00
seven332 9b54fd09c9 Bump gradle tool version 2016-04-27 22:06:30 +08:00
seven332 7f4dc1f131 Fix regex for jack 2016-04-27 21:58:56 +08:00
seven332 5638832c05 Use image library 2016-04-27 21:15:01 +08:00
seven332 a7e8b96b4c Change gallery_list_column_width to 480dp 2016-04-26 18:04:39 +08:00
seven332 a8df181ff8 Add TODO list 2016-04-26 18:03:45 +08:00
seven332 58acaa7287 Add html-format NOTICE 2016-04-25 17:03:35 +08:00
seven332 b00ed5a360 Bump libraries version 2016-04-25 17:02:05 +08:00
seven332 42eeb4f44c Bump libraries and gradle tool version 2016-04-25 00:10:11 +08:00
seven332 2ccb5d92c9 Bump gradle tool version 2016-04-21 16:41:38 +08:00
seven332 e12a35cb52 Remove DumpBrowsableActivity to fix default app error 2016-04-21 16:41:05 +08:00
391 changed files with 3173 additions and 131575 deletions

No files matched your search

-12
View File
@@ -1,12 +0,0 @@
[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
+4 -843
View File
@@ -1,846 +1,7 @@
======================================================================
EhViewer
======================================================================
Copyright 2014-2016 Hippo Seven
Copyright (C) 2014-2016 Hippo Seven
An Unofficial E-Hentai Application for Android.
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.
香风智乃是最可爱的女孩子。
chino kafuu is the cutest girl.
+1840
View File
File diff suppressed because it is too large. Load diff
+1 -14
View File
@@ -18,8 +18,6 @@ Windows
> git clone https://github.com/seven332/EhViewer
> cd EhViewer
> git submodule update --init
> gradlew app:copyNotice
> gradlew daogenerator:executeDaoGenerator
> gradlew app:assembleDebug
@@ -27,8 +25,6 @@ Linux
$ git clone https://github.com/seven332/EhViewer
$ cd EhViewer
$ git submodule update --init
$ ./gradlew app:copyNotice
$ ./gradlew daogenerator:executeDaoGenerator
$ ./gradlew app:assembleDebug
@@ -36,16 +32,6 @@ Linux
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
@@ -55,6 +41,7 @@ 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
/src/main/assets/NOTICE.html
/build
/src/main/java-gen
manifest-merger-release-report.txt
+37 -48
View File
@@ -1,19 +1,26 @@
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
buildToolsVersion "24.0.0 rc3"
defaultConfig {
applicationId "com.hippo.ehviewer"
minSdkVersion 14
targetSdkVersion 23
versionCode 59
versionName "1.0.6"
versionCode 62
versionName "1.0.9"
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
}
lintOptions {
@@ -30,63 +37,45 @@ 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
}
}
clean {
delete file('src/main/obj').absolutePath
delete file('src/main/libs').absolutePath
}
task copyNotice(type: Copy) {
from '../NOTICE'
from '../NOTICE.html'
into './src/main/assets'
}
tasks.withType(AbstractCompile) {
compileTask -> compileTask.dependsOn copyNotice
}
clean {
delete file('src/main/assets/NOTICE.html').absolutePath
}
dependencies {
compile project(':beerbelly')
compile project(':conaco')
compile project(':easyrecyclerview')
compile project(':okhttp3')
compile project(':yorozuya')
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.github.amlcurran.showcaseview:library:5.4.1'
compile 'com.github.anrwatchdog:anrwatchdog:1.2.0'
compile 'com.github.seven332:unifile:0.1.2'
compile 'com.github.amlcurran.showcaseview:library:5.4.3'
compile 'com.github.seven332:beerbelly:0.1.2'
compile 'com.github.seven332:conaco:0.1.3-eh'
compile 'com.github.seven332:easyrecyclerview:0.1.0'
compile 'com.github.seven332:drawerLayout:0.1.0'
compile 'com.github.seven332:image:0.1.4'
compile 'com.github.seven332:okhttp:3.2.0-eh'
compile 'com.github.seven332:refreshlayout:0.1.0'
compile 'com.github.seven332:ripple: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.3'
compile 'com.github.seven332:yorozuya-collect:0.1.2'
compile 'com.github.seven332:yorozuya-thread:0.1.0'
compile 'com.github.seven332:yorozuya: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'
compile 'org.greenrobot:greendao:2.2.0'
compile 'org.jsoup:jsoup:1.9.1'
testCompile 'junit:junit:4.12'
}
Binary file not shown.
-73
View File
@@ -67,68 +67,6 @@
<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
@@ -178,12 +116,6 @@
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"
@@ -201,10 +133,5 @@
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>
@@ -1,240 +0,0 @@
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();
}
}
@@ -1,218 +0,0 @@
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();
}
}
@@ -1,57 +0,0 @@
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();
}
}
@@ -1,100 +0,0 @@
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,6 +24,9 @@ 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,26 +16,59 @@
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.widget.TextView;
import android.util.Log;
import com.hippo.conaco.Conaco;
import com.hippo.conaco.ConacoTask;
import com.hippo.conaco.Unikery;
import com.hippo.conaco.ValueHolder;
import com.hippo.image.ImageBitmap;
import com.hippo.image.ImageDrawable;
import com.hippo.image.RecycledException;
import com.hippo.widget.ObservedTextView;
public class UnikeryDrawable extends WrapDrawable implements Unikery<Bitmap> {
public class UnikeryDrawable extends WrapDrawable implements Unikery<ImageBitmap>,
ObservedTextView.OnWindowAttachListener {
private static final String TAG = UnikeryDrawable.class.getSimpleName();
private int mTaskId = Unikery.INVALID_ID;
private final TextView mTextView;
private final ObservedTextView mTextView;
private final Conaco<ImageBitmap> mConaco;
private String mUrl;
private ValueHolder<Bitmap> mHolder;
public UnikeryDrawable(TextView textView) {
public UnikeryDrawable(ObservedTextView textView, Conaco<ImageBitmap> conaco) {
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
@@ -54,9 +87,7 @@ public class UnikeryDrawable extends WrapDrawable implements Unikery<Bitmap> {
updateBounds();
if (drawable != null) {
// mTextView.requestLayout() not work!
CharSequence cs = mTextView.getText();
mTextView.setText(cs);
invalidateSelf();
}
}
@@ -71,49 +102,41 @@ public class UnikeryDrawable extends WrapDrawable implements Unikery<Bitmap> {
}
@Override
public void onMiss(Conaco.Source source) {
public void invalidateSelf() {
CharSequence cs = mTextView.getText();
mTextView.setText(cs);
}
@Override
public void onRequest() {
}
public void onMiss(int source) {}
@Override
public void onProgress(long singleReceivedSize, long receivedSize, long totalSize) {
}
public void onRequest() {}
private void removeDrawableAndHolder() {
// Remove drawable
setDrawable(null);
@Override
public void onProgress(long singleReceivedSize, long receivedSize, long totalSize) {}
// Remove holder
if (mHolder != null) {
mHolder.release(this);
mHolder = 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;
}
}
@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());
clearDrawable();
setDrawable(drawable);
drawable.start();
return true;
}
@Override
public void onSetDrawable(Drawable drawable) {
removeDrawableAndHolder();
setDrawable(drawable);
}
@Override
public void onFailure() {
// Empty
@@ -22,15 +22,12 @@ 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;
@@ -41,6 +38,8 @@ 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;
@@ -70,7 +69,9 @@ 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_NATIVE_MEMORY = 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 Thread.UncaughtExceptionHandler mDefaultHandler;
@@ -79,8 +80,8 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
private EhCookieStore mEhCookieStore;
private EhClient mEhClient;
private OkHttpClient mOkHttpClient;
private BitmapHelper mBitmapHelper;
private Conaco<Bitmap> mConaco;
private ImageBitmapHelper mImageBitmapHelper;
private Conaco<ImageBitmap> mConaco;
private LruCache<Long, GalleryDetail> mGalleryDetailCache;
private SimpleDiskCache mSpiderInfoCache;
private DownloadManager mDownloadManager;
@@ -93,15 +94,6 @@ 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);
@@ -146,8 +138,8 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
// Ignore
}
if (DEBUG_NATIVE_MEMORY) {
debugNativeMemory();
if (DEBUG_PRINT_NATIVE_MEMORY || DEBUG_PRINT_IMAGE_COUNT) {
debugPrint();
}
}
@@ -194,7 +186,7 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
public void clearMemoryCache() {
if (null != mConaco) {
mConaco.clearMemoryCache();
mConaco.getBeerBelly().clearMemory();
}
if (null != mGalleryDetailCache) {
mGalleryDetailCache.evictAll();
@@ -210,13 +202,18 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
}
}
private void debugNativeMemory() {
private void debugPrint() {
new Runnable() {
@Override
public void run() {
Log.i(TAG, "Native memory: " + FileUtils.humanReadableByteCount(
Debug.getNativeHeapAllocatedSize(), false));
SimpleHandler.getInstance().postDelayed(this, 3000);
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);
}
}.run();
}
@@ -265,9 +262,9 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mOkHttpClient == null) {
application.mOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.cookieJar(getEhCookieStore(application))
.build();
}
@@ -275,12 +272,12 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
}
@NonNull
public static BitmapHelper getBitmapHelper(@NonNull Context context) {
public static ImageBitmapHelper getImageBitmapHelper(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mBitmapHelper == null) {
application.mBitmapHelper = new BitmapHelper();
if (application.mImageBitmapHelper == null) {
application.mImageBitmapHelper = new ImageBitmapHelper();
}
return application.mBitmapHelper;
return application.mImageBitmapHelper;
}
private static int getMemoryCacheMaxSize(Context context) {
@@ -291,17 +288,17 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
}
@NonNull
public static Conaco<Bitmap> getConaco(@NonNull Context context) {
public static Conaco<ImageBitmap> getConaco(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mConaco == null) {
Conaco.Builder<Bitmap> builder = new Conaco.Builder<>();
Conaco.Builder<ImageBitmap> builder = new Conaco.Builder<>();
builder.hasMemoryCache = true;
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 = getBitmapHelper(context);
builder.objectHelper = getImageBitmapHelper(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.sparse.SparseJLArray;
import com.hippo.yorozuya.collect.SparseJLArray;
import java.io.File;
import java.io.FileInputStream;
@@ -16,25 +16,31 @@
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.conaco.ValueHolder;
import com.hippo.yorozuya.io.InputStreamPipe;
import com.hippo.image.Image;
import com.hippo.image.ImageBitmap;
import com.hippo.streampipe.InputStreamPipe;
import java.io.IOException;
public class BitmapHelper implements ValueHelper<Bitmap> {
public class ImageBitmapHelper implements ValueHelper<ImageBitmap> {
private static final int MAX_CACHE_SIZE = 512 * 512;
@Nullable
@Override
public Bitmap decode(@NonNull InputStreamPipe isPipe) {
public ImageBitmap decode(@NonNull InputStreamPipe isPipe) {
try {
isPipe.obtain();
return BitmapFactory.decodeStream(isPipe.open());
Image image = Image.decode(isPipe.open(), false);
if (image != null) {
return new ImageBitmap(image);
} else {
return null;
}
} catch (OutOfMemoryError e) {
return null;
} catch (IOException e) {
@@ -46,15 +52,26 @@ public class BitmapHelper implements ValueHelper<Bitmap> {
}
@Override
public int sizeOf(@NonNull String key, @NonNull Bitmap value) {
return value.getByteCount();
public int sizeOf(@NonNull String key, @NonNull ImageBitmap value) {
return value.getWidth() * value.getHeight() * 4;
}
@Override
public void onRemove(@NonNull String key, @NonNull ValueHolder<Bitmap> oldValue) {}
public void onAddToMemoryCache(@NonNull ImageBitmap oldValue) {
oldValue.obtain();
}
@Override
public boolean useMemoryCache(@NonNull String key, ValueHolder<Bitmap> holder) {
return true;
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;
} else {
return true;
}
}
}
@@ -255,6 +255,24 @@ 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;
@@ -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;
@@ -63,7 +63,8 @@ public class GalleryInfo implements Parcelable {
public static final Pattern[] S_LANG_PATTERNS = {
Pattern.compile("[(\\[]eng(?:lish)?[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[((\\[]ch(?:inese)?[))\\]]|[汉漢]化|中[国國][语語]|中文", Pattern.CASE_INSENSITIVE),
// [((\[]ch(?:inese)?[))\]]|[汉漢]化|中[国國][语語]|中文
Pattern.compile("[(\uFF08\\[]ch(?:inese)?[)\uFF09\\]]|[汉漢]化|中[国國][语語]|中文", 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.IntList;
import com.hippo.yorozuya.collect.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.IntList;
import com.hippo.yorozuya.collect.IntList;
import java.util.ArrayList;
@@ -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.sparse.SparseIJArray;
import com.hippo.yorozuya.sparse.SparseJLArray;
import com.hippo.yorozuya.collect.LongList;
import com.hippo.yorozuya.collect.SparseIJArray;
import com.hippo.yorozuya.collect.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.sparse.SparseJBArray;
import com.hippo.yorozuya.sparse.SparseJLArray;
import com.hippo.yorozuya.collect.LongList;
import com.hippo.yorozuya.collect.SparseJBArray;
import com.hippo.yorozuya.collect.SparseJLArray;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -28,8 +28,8 @@ 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;
@@ -84,7 +84,7 @@ public class DirGalleryProvider extends GalleryProvider implements Runnable {
}
@Override
public void request(int index) {
protected void onRequest(int index) {
synchronized (mRequests) {
if (!mRequests.contains(index) && index != mDecodingIndex.get()) {
mRequests.add(index);
@@ -95,7 +95,12 @@ public class DirGalleryProvider extends GalleryProvider implements Runnable {
}
@Override
public void cancelRequest(int index) {
protected void onForceRequest(int index) {
onRequest(index);
}
@Override
public void onCancelRequest(int index) {
synchronized (mRequests) {
mRequests.remove(Integer.valueOf(index));
}
@@ -111,7 +111,7 @@ public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.On
}
@Override
public void request(int index) {
protected void onRequest(int index) {
if (mSpiderQueen != null) {
Object object = mSpiderQueen.request(index);
if (object instanceof Float) {
@@ -125,7 +125,7 @@ public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.On
}
@Override
public void forceRequest(int index) {
protected void onForceRequest(int index) {
if (mSpiderQueen != null) {
Object object = mSpiderQueen.forceRequest(index);
if (object instanceof Float) {
@@ -139,7 +139,7 @@ public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.On
}
@Override
public void cancelRequest(int index) {
protected void onCancelRequest(int index) {
if (mSpiderQueen != null) {
mSpiderQueen.cancelRequest(index);
}
@@ -21,15 +21,25 @@ import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import com.hippo.beerbelly.LruCache;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.gl.view.GLRoot;
import com.hippo.image.Image;
import com.hippo.image.ImageWrapper;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.ConcurrentPool;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.OSUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class GalleryProvider {
@@ -48,6 +58,8 @@ public abstract class GalleryProvider {
private volatile GalleryProviderListener mGalleryProviderListener;
private volatile GLRoot mGLRoot;
private final ImageCache mImageCache = new ImageCache();
private boolean mStarted = false;
@UiThread
@@ -63,25 +75,40 @@ public abstract class GalleryProvider {
@UiThread
public void stop() {
OSUtils.checkMainLoop();
mImageCache.close();
}
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 final void request(int index) {
ImageWrapper imageWrapper = mImageCache.get(index);
if (imageWrapper != null) {
notifyPageSucceed(index, imageWrapper);
} else {
onRequest(index);
}
}
public abstract void cancelRequest(int index);
public final void forceRequest(int index) {
onForceRequest(index);
}
protected abstract void onRequest(int index);
protected abstract void onForceRequest(int index);
public final void cancelRequest(int index) {
onCancelRequest(index);
}
protected abstract void onCancelRequest(int index);
public abstract String getError();
@@ -126,6 +153,12 @@ public abstract class GalleryProvider {
}
public void notifyPageSucceed(int index, Image image) {
ImageWrapper imageWrapper = new ImageWrapper(image);
mImageCache.add(index, imageWrapper);
notifyPageSucceed(index, imageWrapper);
}
public void notifyPageSucceed(int index, ImageWrapper image) {
notify(NotifyTask.TYPE_SUCCEED, index, 0.0f, image, null);
}
@@ -133,7 +166,7 @@ public abstract class GalleryProvider {
notify(NotifyTask.TYPE_FAILED, index, 0.0f, null, error);
}
private void notify(@NotifyTask.Type int type, int index, float percent, Image image, String error) {
private void notify(@NotifyTask.Type int type, int index, float percent, ImageWrapper image, String error) {
GalleryProviderListener listener = mGalleryProviderListener;
if (listener == null) {
return;
@@ -171,7 +204,7 @@ public abstract class GalleryProvider {
private int mType;
private int mIndex;
private float mPercent;
private Image mImage;
private ImageWrapper mImage;
private String mError;
public NotifyTask(GalleryProviderListener galleryProviderListener, ConcurrentPool<NotifyTask> pool) {
@@ -179,7 +212,7 @@ public abstract class GalleryProvider {
mPool = pool;
}
public void setData(@Type int type, int index, float percent, Image image, String error) {
public void setData(@Type int type, int index, float percent, ImageWrapper image, String error) {
mType = type;
mIndex = index;
mPercent = percent;
@@ -220,4 +253,67 @@ public abstract class GalleryProvider {
return false;
}
}
private static class ImageCache extends LruCache<Integer, ImageWrapper> {
private static final long MAX_CACHE_SIZE = 128 * 1024 * 1024;
private static final long MIN_CACHE_SIZE = 32 * 1024 * 1024;
private static final String PROCFS_MEMFILE = "/proc/meminfo";
private static final Pattern PROCFS_MEMFILE_FORMAT =
Pattern.compile("^([a-zA-Z]*):[ \t]*([0-9]*)[ \t]kB");
private static final String MEMTOTAL_STRING = "MemTotal";
private static long sMemTotal = -2L;
private static long getTotalMemory() {
if (sMemTotal != -2L) {
return sMemTotal;
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(PROCFS_MEMFILE), 64);
String line;
while ((line = reader.readLine()) != null) {
Matcher matcher = PROCFS_MEMFILE_FORMAT.matcher(line);
if (matcher.find() && MEMTOTAL_STRING.equals(matcher.group(1))) {
long mem = NumberUtils.parseLongSafely(matcher.group(2), -1L);
if (mem != -1L) {
mem *= 1024;
}
sMemTotal = mem;
return mem;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(reader);
}
sMemTotal = -1L;
return -1L;
}
public ImageCache() {
super((int) MathUtils.clamp(getTotalMemory() / 16, MIN_CACHE_SIZE, MAX_CACHE_SIZE));
}
public void add(Integer key, ImageWrapper value) {
if (value.obtain()) {
put(key, value);
}
}
@Override
protected int sizeOf(Integer key, ImageWrapper value) {
return value.getWidth() * value.getHeight() * 4;
}
@Override
protected void entryRemoved(boolean evicted, Integer key, ImageWrapper oldValue, ImageWrapper newValue) {
if (oldValue != null) {
oldValue.release();
}
}
}
}
@@ -16,7 +16,7 @@
package com.hippo.ehviewer.gallery;
import com.hippo.image.Image;
import com.hippo.image.ImageWrapper;
public interface GalleryProviderListener {
@@ -26,7 +26,7 @@ public interface GalleryProviderListener {
void onPagePercent(int index, float percent);
void onPageSucceed(int index, Image image);
void onPageSucceed(int index, ImageWrapper image);
void onPageFailed(int index, String error);
@@ -26,8 +26,8 @@ import com.hippo.ehviewer.R;
import com.hippo.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.PriorityThread;
import com.hippo.yorozuya.StringUtils;
import com.hippo.yorozuya.thread.PriorityThread;
import java.io.File;
import java.io.FileNotFoundException;
@@ -85,7 +85,7 @@ public class ZipGalleryProvider extends GalleryProvider implements Runnable {
}
@Override
public void request(int index) {
protected void onRequest(int index) {
synchronized (mRequests) {
if (!mRequests.contains(index) && index != mDecodingIndex.get()) {
mRequests.add(index);
@@ -96,7 +96,12 @@ public class ZipGalleryProvider extends GalleryProvider implements Runnable {
}
@Override
public void cancelRequest(int index) {
protected void onForceRequest(int index) {
onRequest(index);
}
@Override
protected void onCancelRequest(int index) {
synchronized (mRequests) {
mRequests.remove(Integer.valueOf(index));
}
@@ -19,8 +19,8 @@ package com.hippo.ehviewer.gallery.gl;
import android.content.Context;
import com.hippo.gl.glrenderer.BasicTexture;
import com.hippo.gl.glrenderer.ImageMovableTextTexture;
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;
@@ -49,7 +49,7 @@ public class GalleryPageView extends GLFrameLayout {
private int mIndex = INVALID_INDEX;
public GalleryPageView(Context context, MovableTextTexture pageTextTexture,
public GalleryPageView(Context context, ImageMovableTextTexture pageTextTexture,
int progressColor, int progressSize) {
// Add image
mImage = new ImageView();
@@ -28,7 +28,7 @@ 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.ImageMovableTextTexture;
import com.hippo.gl.glrenderer.StringTexture;
import com.hippo.gl.glrenderer.Texture;
import com.hippo.gl.util.GalleryUtils;
@@ -90,7 +90,7 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
private static final int METHOD_ON_ATTACH_TO_ROOT = 20;
private final Context mContext;
private MovableTextTexture mPageTextTexture;
private ImageMovableTextTexture mPageTextTexture;
private final GestureRecognizer mGestureRecognizer;
private Adapter mAdapter;
@@ -116,7 +116,6 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
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();
@@ -142,7 +141,6 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
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,
@@ -230,7 +228,7 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
@SuppressWarnings("deprecation")
private void onAttachToRootInternal() {
if (null == mPageTextTexture) {
mPageTextTexture = MovableTextTexture.create(Typeface.DEFAULT,
mPageTextTexture = ImageMovableTextTexture.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'});
@@ -547,7 +545,6 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
}
private void onDownInternal(float x, float y) {
mTouched = true;
mScale = false;
mScroll = false;
mFirstScroll = true;
@@ -557,7 +554,6 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
}
private void onUpInternal() {
mTouched = false;
if (mLayoutManager != null) {
mLayoutManager.onUp();
}
@@ -803,7 +799,7 @@ public class GalleryView extends GLView implements GestureRecognizer.Listener {
@RenderThread
public GalleryPageView findPageByIndex(int id) {
if (!mPause && mLayoutManager != null) {
if (mLayoutManager != null) {
return mLayoutManager.findPageByIndex(id);
} else {
return null;
@@ -184,8 +184,8 @@ public class PagerLayoutManager extends GalleryView.LayoutManager {
@Override
public void onAttach(GalleryView.Adapter adapter) {
AssertUtils.assertEquals("The PagerLayoutManager is attached", mAdapter, null);
AssertUtils.assertNotEquals("The adapter is null", adapter, null);
AssertUtils.assertNull("The PagerLayoutManager is attached", mAdapter);
AssertUtils.assertNotNull("The adapter is null", adapter);
mAdapter = adapter;
// Reset parameters
resetParameters();
@@ -232,7 +232,7 @@ public class PagerLayoutManager extends GalleryView.LayoutManager {
@Override
public GalleryView.Adapter onDetach() {
AssertUtils.assertNotEquals("The PagerLayoutManager is not attached", mAdapter, null);
AssertUtils.assertNotNull("The PagerLayoutManager is not attached", mAdapter);
// Cancel all animations
cancelAllAnimations();
@@ -293,7 +293,7 @@ public class PagerLayoutManager extends GalleryView.LayoutManager {
public void onFill() {
GalleryView.Adapter adapter = mAdapter;
GalleryView galleryView = mGalleryView;
AssertUtils.assertNotEquals("The PagerLayoutManager is not attached", adapter, null);
AssertUtils.assertNotNull("The PagerLayoutManager is not attached", adapter);
int width = galleryView.getWidth();
int height = galleryView.getHeight();
@@ -703,7 +703,7 @@ public class PagerLayoutManager extends GalleryView.LayoutManager {
@Override
public void onDataChanged() {
AssertUtils.assertNotEquals("The PagerLayoutManager is not attached", mAdapter, null);
AssertUtils.assertNotNull("The PagerLayoutManager is not attached", mAdapter);
// Cancel all animations
cancelAllAnimations();
@@ -112,8 +112,8 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
@Override
public void onAttach(GalleryView.Adapter adapter) {
AssertUtils.assertEquals("The ScrollLayoutManager is attached", mAdapter, null);
AssertUtils.assertNotEquals("The iterator is null", adapter, null);
AssertUtils.assertNull("The ScrollLayoutManager is attached", mAdapter);
AssertUtils.assertNotNull("The iterator is null", adapter);
mAdapter = adapter;
// Reset parameters
resetParameters();
@@ -151,7 +151,7 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
@Override
public GalleryView.Adapter onDetach() {
AssertUtils.assertNotEquals("The PagerLayoutManager is not attached", mAdapter, null);
AssertUtils.assertNotNull("The PagerLayoutManager is not attached", mAdapter);
// Cancel all animations
cancelAllAnimations();
@@ -396,7 +396,7 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
public void onFill() {
GalleryView.Adapter adapter = mAdapter;
GalleryView galleryView = mGalleryView;
AssertUtils.assertNotEquals("The PagerLayoutManager is not attached", adapter, null);
AssertUtils.assertNotNull("The PagerLayoutManager is not attached", adapter);
int size = adapter.size();
String errorStr = adapter.getError();
@@ -831,7 +831,7 @@ public class ScrollLayoutManager extends GalleryView.LayoutManager {
@Override
public void onDataChanged() {
AssertUtils.assertNotEquals("The PagerLayoutManager is not attached", mAdapter, null);
AssertUtils.assertNotNull("The PagerLayoutManager is not attached", mAdapter);
// Cancel all animations
cancelAllAnimations();
@@ -30,14 +30,14 @@ import com.hippo.ehviewer.client.data.GalleryInfo;
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;
@@ -48,18 +48,18 @@ import com.hippo.ehviewer.client.parser.GalleryPageUrlParser;
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.io.InputStreamPipe;
import com.hippo.yorozuya.io.OutputStreamPipe;
import com.hippo.yorozuya.sparse.SparseJLArray;
import com.hippo.yorozuya.collect.SparseJLArray;
import com.hippo.yorozuya.thread.PriorityThread;
import com.hippo.yorozuya.thread.PriorityThreadFactory;
import java.io.IOException;
import java.io.InputStream;
@@ -1,106 +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;
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);
}
}
}
@@ -1,213 +0,0 @@
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()));
}
}
@@ -1,21 +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;
// 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 {}
@@ -62,7 +62,7 @@ import com.hippo.ehviewer.widget.GalleryGuideView;
import com.hippo.ehviewer.widget.ReversibleSeekBar;
import com.hippo.gl.glrenderer.ImageTexture;
import com.hippo.gl.view.GLRootView;
import com.hippo.image.Image;
import com.hippo.image.ImageWrapper;
import com.hippo.unifile.UniFile;
import com.hippo.util.SystemUiHelper;
import com.hippo.widget.ColorView;
@@ -99,6 +99,8 @@ public class GalleryActivity extends EhActivity
private GalleryInfo mGalleryInfo;
private int mPage;
@Nullable
private GLRootView mGLRootView;
@Nullable
private GalleryView mGalleryView;
@@ -259,9 +261,9 @@ public class GalleryActivity extends EhActivity
mGalleryProvider.start();
setContentView(R.layout.activity_gallery);
GLRootView glRootView = (GLRootView) ViewUtils.$$(this, R.id.gl_root_view);
mGalleryProvider.setGLRoot(glRootView);
mUploader = new ImageTexture.Uploader(glRootView);
mGLRootView = (GLRootView) ViewUtils.$$(this, R.id.gl_root_view);
mGalleryProvider.setGLRoot(mGLRootView);
mUploader = new ImageTexture.Uploader(mGLRootView);
int startPage;
if (savedInstanceState == null) {
@@ -273,7 +275,7 @@ public class GalleryActivity extends EhActivity
mGalleryView = new GalleryView(this, new GalleryAdapter(), this,
Settings.getReadingDirection(), Settings.getPageScaling(),
Settings.getStartPosition(), startPage);
glRootView.setContentPane(mGalleryView);
mGLRootView.setContentPane(mGalleryView);
// System UI helper
if (Settings.getReadingFullscreen()) {
@@ -343,6 +345,7 @@ public class GalleryActivity extends EhActivity
@Override
protected void onDestroy() {
super.onDestroy();
mGLRootView = null;
mGalleryView = null;
if (mUploader != null) {
mUploader.clear();
@@ -366,6 +369,24 @@ public class GalleryActivity extends EhActivity
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);
@@ -549,20 +570,26 @@ public class GalleryActivity extends EhActivity
}
@Override
public void onPageSucceed(int index, Image image) {
public void onPageSucceed(int index, ImageWrapper image) {
GalleryPageView page = findPageByIndex(index);
if (page != null) {
ImageTexture imageTexture = new ImageTexture(image);
if (mUploader != null) {
mUploader.addTexture(imageTexture);
if (image.obtain()) {
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 {
// The image is recycled, request again.
// TODO request loop ?
if (mGalleryProvider != null) {
mGalleryProvider.request(index);
}
}
page.showImage();
page.setImage(imageTexture);
page.setPage(index + 1);
page.setProgress(GalleryPageView.PROGRESS_GONE);
page.setError(null, null);
} else {
image.recycle();
}
}
@@ -33,7 +33,7 @@ public class LicenseActivity extends ToolbarActivity {
super.onCreate(savedInstanceState);
mWebView = new WebView(this);
mWebView.loadUrl("file:///android_asset/NOTICE");
mWebView.loadUrl("file:///android_asset/NOTICE.html");
setContentView(mWebView);
setNavigationIcon(R.drawable.v_arrow_left_dark_x24);
@@ -34,10 +34,12 @@ 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);
}
@@ -50,6 +52,8 @@ 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);
}
@@ -56,6 +56,8 @@ 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;
@@ -75,8 +77,10 @@ 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;
@@ -86,11 +90,15 @@ 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.LongList;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.ViewUtils;
import com.hippo.yorozuya.collect.LongList;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
@@ -289,7 +297,7 @@ public class DownloadsScene extends ToolbarScene
mAdapter.setHasStableIds(true);
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new AutoStaggeredGridLayoutManager(0, StaggeredGridLayoutManager.VERTICAL);
mLayoutManager.setColumnSize(resources.getDimensionPixelOffset(R.dimen.gallery_list_column_width));
mLayoutManager.setColumnSize(resources.getDimensionPixelOffset(Settings.getDetailSizeResId()));
mLayoutManager.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_MIN_SIZE);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
@@ -1137,7 +1145,17 @@ public class DownloadsScene extends ToolbarScene
return;
}
DownloadInfo info = mList.get(position);
holder.thumb.load(EhCacheKeyFactory.getThumbKey(info.gid), info.thumb);
DataContainer container = null;
UniFile dir = SpiderDen.getGalleryDownloadDir(info);
if (dir != null) {
UniFile file = dir.createFile(".thumb");
if (file != null) {
container = new ThumbDataContainer(file);
}
}
holder.thumb.load(EhCacheKeyFactory.getThumbKey(info.gid), info.thumb, container, true);
holder.title.setText(EhUtils.getSuitableTitle(info));
holder.uploader.setText(info.uploader);
holder.rating.setRating(info.rating);
@@ -1198,4 +1216,45 @@ public class DownloadsScene extends ToolbarScene
}
}
}
private class ThumbDataContainer implements DataContainer {
@NonNull
private final UniFile mFile;
/**
* @param file the thumb file
*/
public ThumbDataContainer(@NonNull UniFile file) {
mFile = file;
}
@Override
public void onUrlMoved(String requestUrl, String responseUrl) {}
@Override
public boolean save(InputStream is, long length, String mediaType, ProgressNotifier notify) {
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() {
return new UniFileInputStreamPipe(mFile);
}
@Override
public void remove() {
mFile.delete();
}
}
}
@@ -95,7 +95,7 @@ abstract class GalleryAdapter extends RecyclerView.Adapter<GalleryHolder> {
switch (type) {
default:
case GalleryAdapter.TYPE_LIST: {
int columnWidth = mResources.getDimensionPixelOffset(R.dimen.gallery_list_column_width);
int columnWidth = mResources.getDimensionPixelOffset(Settings.getDetailSizeResId());
mLayoutManager.setColumnSize(columnWidth);
mLayoutManager.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_MIN_SIZE);
if (null != mGirdDecoration) {
@@ -74,14 +74,15 @@ 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 java.util.ArrayList;
import java.util.List;
@@ -616,7 +617,7 @@ public final class GalleryCommentsScene extends ToolbarScene
return new CommentHolder(mInflater.inflate(R.layout.item_gallery_comment, parent, false));
}
public CharSequence generateComment(Context context, TextView textView, GalleryComment comment) {
public CharSequence generateComment(Context context, ObservedTextView textView, GalleryComment comment) {
SpannableStringBuilder ssb = Html.fromHtml(comment.comment, new URLImageGetter(textView,
EhApplication.getConaco(context)), null);
@@ -96,6 +96,7 @@ 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;
@@ -869,7 +870,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));
TextView c = (TextView) v.findViewById(R.id.comment);
ObservedTextView c = (ObservedTextView) v.findViewById(R.id.comment);
c.setMaxLines(5);
c.setText(Html.fromHtml(comment.comment,
new URLImageGetter(c, EhApplication.getConaco(context)), null));
@@ -48,6 +48,7 @@ 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;
@@ -122,7 +123,7 @@ public class HistoryScene extends ToolbarScene
mRecyclerView.setItemAnimator(animator);
AutoStaggeredGridLayoutManager layoutManager = new AutoStaggeredGridLayoutManager(
0, StaggeredGridLayoutManager.VERTICAL);
layoutManager.setColumnSize(resources.getDimensionPixelOffset(R.dimen.gallery_list_column_width));
layoutManager.setColumnSize(resources.getDimensionPixelOffset(Settings.getDetailSizeResId()));
layoutManager.setStrategy(AutoStaggeredGridLayoutManager.STRATEGY_MIN_SIZE);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setSelector(Ripple.generateRippleDrawable(context, false));
@@ -43,7 +43,6 @@ 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;
@@ -86,7 +85,6 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
private ViewTransition mViewTransition;
private SearchDatabase mSearchDatabase;
private DictManager mDictManager;
private List<String> mSuggestionList;
private ArrayAdapter mSuggestionAdapter;
@@ -116,7 +114,6 @@ 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);
@@ -173,11 +170,8 @@ 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();
@@ -485,15 +479,10 @@ 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 class SearchDatabase {
public final class SearchDatabase {
private static final String TAG = SearchDatabase.class.getSimpleName();
@@ -41,7 +41,7 @@ public class SearchDatabase {
private static final int MAX_HISTORY = 100;
private SQLiteDatabase mDatabase;
private final SQLiteDatabase mDatabase;
private static SearchDatabase sInstance;
@@ -60,6 +60,7 @@ public 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)) {
@@ -126,11 +127,10 @@ public class SearchDatabase {
}
mDatabase.delete(TABLE_SUGGESTIONS, selection, null);
} catch (RuntimeException e) {
Say.e(TAG, "truncateHistory", e);
Log.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
@@ -53,7 +53,7 @@ public abstract class BasicTexture implements Texture {
protected GLCanvas mCanvasRef = null;
private final static WeakHashMap<BasicTexture, Object> sAllTextures
= new WeakHashMap<>();
private static ThreadLocal<Class> sInFinalizer = new ThreadLocal<>();
private static final ThreadLocal<Class> sInFinalizer = new ThreadLocal<>();
protected BasicTexture(GLCanvas canvas, int id, int state) {
setAssociatedCanvas(canvas);
@@ -20,7 +20,7 @@ package com.hippo.gl.glrenderer;
// Before drawing, setSize() should be called.
public class ExtTexture extends BasicTexture {
private int mTarget;
private final int mTarget;
public ExtTexture(GLCanvas canvas, int target) {
GLId glId = canvas.getGLId();
@@ -24,8 +24,8 @@ import android.opengl.GLUtils;
import android.opengl.Matrix;
import android.util.Log;
import com.hippo.yorozuya.IntArray;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.collect.IntList;
import java.nio.Buffer;
import java.nio.ByteBuffer;
@@ -166,7 +166,7 @@ public class GLES20Canvas implements GLCanvas {
// Keep track of restore state
private float[] mMatrices = new float[INITIAL_RESTORE_STATE_SIZE * MATRIX_SIZE];
private float[] mAlphas = new float[INITIAL_RESTORE_STATE_SIZE];
private IntArray mSaveFlags = new IntArray();
private final IntList mSaveFlags = new IntList();
private int mCurrentAlphaIndex = 0;
private int mCurrentMatrixIndex = 0;
@@ -176,20 +176,20 @@ public class GLES20Canvas implements GLCanvas {
private int mHeight;
// Projection matrix
private float[] mProjectionMatrix = new float[MATRIX_SIZE];
private final float[] mProjectionMatrix = new float[MATRIX_SIZE];
// Screen size for when we aren't bound to a texture
private int mScreenWidth;
private int mScreenHeight;
// GL programs
private int mDrawProgram;
private int mTextureProgram;
private int mOesTextureProgram;
private int mMeshProgram;
private final int mDrawProgram;
private final int mTextureProgram;
private final int mOesTextureProgram;
private final int mMeshProgram;
// GL buffer containing BOX_COORDINATES
private int mBoxCoordinates;
private final int mBoxCoordinates;
// Handle indices -- common
private static final int INDEX_POSITION = 0;
@@ -268,8 +268,8 @@ public class GLES20Canvas implements GLCanvas {
new UniformShaderParameter(ALPHA_UNIFORM), // INDEX_ALPHA
};
private final IntArray mUnboundTextures = new IntArray();
private final IntArray mDeleteBuffers = new IntArray();
private final IntList mUnboundTextures = new IntList();
private final IntList mDeleteBuffers = new IntList();
// Keep track of statistics for debugging
private int mCountDrawMesh = 0;
@@ -279,10 +279,10 @@ public class GLES20Canvas implements GLCanvas {
// Buffer for framebuffer IDs -- we keep track so we can switch the attached
// texture.
private int[] mFrameBuffer = new int[1];
private final int[] mFrameBuffer = new int[1];
// Bound textures.
private ArrayList<RawTexture> mTargetTextures = new ArrayList<RawTexture>();
private final ArrayList<RawTexture> mTargetTextures = new ArrayList<>();
// Temporary variables used within calculations
private final float[] mTempMatrix = new float[32];
@@ -492,7 +492,7 @@ public class GLES20Canvas implements GLCanvas {
@Override
public void restore() {
int restoreFlags = mSaveFlags.removeLast();
int restoreFlags = mSaveFlags.removeAt(mSaveFlags.size() - 1);
boolean restoreAlpha = (restoreFlags & SAVE_FLAG_ALPHA) == SAVE_FLAG_ALPHA;
if (restoreAlpha) {
mCurrentAlphaIndex--;
@@ -869,7 +869,7 @@ public class GLES20Canvas implements GLCanvas {
@Override
public void deleteRecycledResources() {
synchronized (mUnboundTextures) {
IntArray ids = mUnboundTextures;
IntList ids = mUnboundTextures;
if (mUnboundTextures.size() > 0) {
mGLId.glDeleteTextures(null, ids.size(), ids.getInternalArray(), 0);
ids.clear();
@@ -0,0 +1,210 @@
/*
* 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.glrenderer;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.image.Image;
import com.hippo.image.ImageWrapper;
import java.util.Arrays;
public class ImageMovableTextTexture extends ImageSpriteTexture {
private final char[] mCharacters;
private final float[] mWidths;
private final float mHeight;
private final float mMaxWidth;
public ImageMovableTextTexture(@NonNull ImageWrapper image, int count, int[] rects,
char[] characters, float[] widths, float height, float maxWidth) {
super(image, 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
*/
@Nullable
public static ImageMovableTextTexture 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);
// Calculate 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;
}
}
Image image = Image.create(bitmap);
bitmap.recycle();
if (image == null) {
return null;
}
ImageWrapper imageWrapper = new ImageWrapper(image);
if (imageWrapper.obtain()) {
return new ImageMovableTextTexture(imageWrapper, length, rects, characters, widths, height, maxWidth);
} else {
return null;
}
}
}
@@ -0,0 +1,90 @@
/*
* 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.glrenderer;
import android.graphics.RectF;
import android.support.annotation.NonNull;
import com.hippo.image.ImageWrapper;
import com.hippo.yorozuya.AssertUtils;
public class ImageSpriteTexture extends ImageTexture {
private final int mCount;
private final int[] mRects;
private final RectF mTempSource = new RectF();
private final RectF mTempTarget = new RectF();
public ImageSpriteTexture(@NonNull ImageWrapper image, int count, int[] rects) {
super(image);
AssertUtils.assertEquals("rects.length must be count * 4", count * 4, rects.length);
mCount = count;
mRects = rects;
}
public int getCount() {
return mCount;
}
public void drawSprite(GLCanvas canvas, int index, int x, int y) {
int[] rects = mRects;
int offset = index * 4;
int sourceX = rects[offset];
int sourceY = rects[offset + 1];
int sourceWidth = rects[offset + 2];
int sourceHeight = rects[offset + 3];
mTempSource.set(sourceX, sourceY, sourceX + sourceWidth, sourceY + sourceHeight);
mTempTarget.set(x, y, x + sourceWidth, y + sourceHeight);
draw(canvas, mTempSource, mTempTarget);
}
public void drawSprite(GLCanvas canvas, int index, int x, int y, int width, int height) {
int[] rects = mRects;
int offset = index * 4;
int sourceX = rects[offset];
int sourceY = rects[offset + 1];
mTempSource.set(sourceX, sourceY, sourceX + rects[offset + 2], sourceY + rects[offset + 3]);
mTempTarget.set(x, y, x + width, y + height);
draw(canvas, mTempSource, mTempTarget);
}
public void drawSpriteMixed(GLCanvas canvas, int index, int color, float ratio, int x, int y) {
int[] rects = mRects;
int offset = index * 4;
int sourceX = rects[offset];
int sourceY = rects[offset + 1];
int sourceWidth = rects[offset + 2];
int sourceHeight = rects[offset + 3];
mTempSource.set(sourceX, sourceY, sourceX + sourceWidth, sourceY + sourceHeight);
mTempTarget.set(x, y, x + sourceWidth, y + sourceHeight);
drawMixed(canvas, color, ratio, mTempSource, mTempTarget);
}
public void drawSpriteMixed(GLCanvas canvas, int index, int color, float ratio,
int x, int y, int width, int height) {
int[] rects = mRects;
int offset = index * 4;
int sourceX = rects[offset];
int sourceY = rects[offset + 1];
mTempSource.set(sourceX, sourceY, sourceX + rects[offset + 2],
sourceY + rects[offset + 3]);
mTempTarget.set(x, y, x + width, y + height);
drawMixed(canvas, color, ratio, mTempSource, mTempTarget);
}
}
@@ -24,9 +24,9 @@ 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 com.hippo.image.ImageWrapper;
import com.hippo.yorozuya.thread.PVLock;
import com.hippo.yorozuya.thread.PriorityThreadFactory;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -66,10 +66,10 @@ public class ImageTexture implements Texture, Animatable {
private static Tile sLargeFreeTileHead = null;
private static final Object sFreeTileLock = new Object();
private final Image mImage;
private final ImageWrapper mImage;
private int mUploadIndex = 0;
private final Tile[] mTiles; // Can be modified in different threads.
// Should be protected by "synchronized."
// Should be protected by "synchronized."
private final int mWidth;
private final int mHeight;
@@ -79,7 +79,8 @@ public class ImageTexture implements Texture, Animatable {
private final AtomicBoolean mFrameDirty = new AtomicBoolean();
private boolean mImageBusy = false;
private final AtomicBoolean mNeedRecycle = new AtomicBoolean();
private final AtomicBoolean mNeedRelease = new AtomicBoolean();
private final AtomicBoolean mReleased = new AtomicBoolean();
private final AtomicReference<Thread> mAnimateThread = new AtomicReference<>();
@@ -142,7 +143,7 @@ public class ImageTexture implements Texture, Animatable {
private int mTileType;
public int offsetX;
public int offsetY;
public Image image;
public ImageWrapper image;
public Tile nextFreeTile;
public int contentWidth;
public int contentHeight;
@@ -244,8 +245,8 @@ public class ImageTexture implements Texture, Animatable {
long lastDelay = -1L;
synchronized (mImage) {
// Check recycled
if (mImage.isRecycled()) {
// Check released
if (mReleased.get()) {
return;
}
// Check image busy
@@ -253,8 +254,8 @@ public class ImageTexture implements Texture, Animatable {
// Image is busy, means it is recycling
return;
}
if (mNeedRecycle.get()) {
// Need recycle
if (mNeedRelease.get()) {
// Need release
return;
}
// Obtain image
@@ -270,7 +271,7 @@ public class ImageTexture implements Texture, Animatable {
} catch (InterruptedException e) {
interrupted = true;
}
if (!interrupted && !mNeedRecycle.get()) {
if (!interrupted && !mNeedRelease.get()) {
mImage.complete();
}
sPVLock.v();
@@ -284,15 +285,15 @@ public class ImageTexture implements Texture, Animatable {
mImageBusy = false;
}
if (interrupted || mNeedRecycle.get() || frameCount <= 1) {
if (interrupted || mNeedRelease.get() || frameCount <= 1) {
return;
}
while (!Thread.currentThread().isInterrupted()) {
// Obtain
synchronized (mImage) {
// Check recycled
if (mImage.isRecycled()) {
// Check released
if (mReleased.get()) {
return;
}
// Check image busy
@@ -300,8 +301,8 @@ public class ImageTexture implements Texture, Animatable {
// Image is busy, means it is recycling
return;
}
if (mNeedRecycle.get()) {
// Need recycle
if (mNeedRelease.get()) {
// Need release
return;
}
// Obtain image
@@ -338,11 +339,11 @@ public class ImageTexture implements Texture, Animatable {
public void run() {
doRun();
while (mNeedRecycle.get()) {
while (mNeedRelease.get()) {
// Obtain
synchronized (mImage) {
// Check recycled
if (mImage.isRecycled()) {
// Check released
if (mReleased.get()) {
break;
}
// Check image busy
@@ -354,7 +355,8 @@ public class ImageTexture implements Texture, Animatable {
mImageBusy = true;
}
mImage.recycle();
mImage.release();
mReleased.lazySet(true);
synchronized (mImage) {
// Release image
@@ -366,7 +368,10 @@ public class ImageTexture implements Texture, Animatable {
}
}
public ImageTexture(@NonNull Image image) {
/**
* Call {@link ImageWrapper#obtain()} first
*/
public ImageTexture(@NonNull ImageWrapper image) {
mImage = image;
int width = mWidth = image.getWidth();
int height = mHeight = image.getHeight();
@@ -457,7 +462,7 @@ public class ImageTexture implements Texture, Animatable {
@Override
public void start() {
if (mImage.isRecycled() || (mImage.isCompleted() && mImage.getFrameCount() <= 1)) {
if (mReleased.get() || (mImage.isCompleted() && mImage.getFrameCount() <= 1)) {
return;
}
@@ -471,7 +476,7 @@ public class ImageTexture implements Texture, Animatable {
@Override
public void stop() {
if (!mImage.isRecycled() && (mImage.isCompleted() && mImage.getFrameCount() > 1)) {
if (!mReleased.get() && (mImage.isCompleted() && mImage.getFrameCount() > 1)) {
Thread thread = mAnimateThread.getAndSet(null);
if (null != thread) {
thread.interrupt();
@@ -481,7 +486,7 @@ public class ImageTexture implements Texture, Animatable {
@Override
public boolean isRunning() {
return false;
return mAnimateThread.get() != null;
}
@@ -654,24 +659,25 @@ public class ImageTexture implements Texture, Animatable {
mTile.free();
}
boolean recycleNow;
boolean releaseNow;
synchronized (mImage) {
if (!mImageBusy) {
recycleNow = true;
releaseNow = true;
mImageBusy = true;
} else {
recycleNow = false;
releaseNow = false;
}
}
if (recycleNow) {
mImage.recycle();
if (releaseNow) {
mImage.release();
mReleased.set(true);
synchronized (mImage) {
mImageBusy = false;
}
} else {
mNeedRecycle.set(true);
mNeedRelease.set(true);
}
Thread thread = mAnimateThread.getAndSet(null);
@@ -13,12 +13,12 @@ import java.util.Arrays;
* <br>
* Only support single line now
*/
public class MovableTextTexture extends SpriteTexture {
public final class MovableTextTexture extends SpriteTexture {
private char[] mCharacters;
private float[] mWidths;
private float mHeight;
private float mMaxWidth;
private final char[] mCharacters;
private final float[] mWidths;
private final float mHeight;
private final float mMaxWidth;
private MovableTextTexture(Bitmap bitmap, int count, int[] rects, char[] characters,
float[] widths, float height, float maxWidth) {
@@ -137,7 +137,7 @@ public class MovableTextTexture extends SpriteTexture {
float[] widths = new float[length];
paint.getTextWidths(characters, 0, length, widths);
// Caculate bitmap size
// Calculate bitmap size
float maxWidth = 0.0f;
for (float f : widths) {
maxWidth = Math.max(maxWidth, f);
@@ -7,11 +7,11 @@ import com.hippo.yorozuya.AssertUtils;
public class SpriteTexture extends TiledTexture {
private int mCount;
private int[] mRects;
private final int mCount;
private final int[] mRects;
private RectF mTempSource = new RectF();
private RectF mTempTarget = new RectF();
private final RectF mTempSource = new RectF();
private final RectF mTempTarget = new RectF();
public SpriteTexture(Bitmap bitmap, boolean isOpaque, int count, int[] rects) {
super(bitmap, isOpaque);
@@ -25,9 +25,9 @@ public class TextureUploader implements GLRoot.OnGLIdleListener {
private static final int QUOTA_PER_FRAME = 1;
private final ArrayDeque<UploadedTexture> mFgTextures =
new ArrayDeque<UploadedTexture>(INIT_CAPACITY);
new ArrayDeque<>(INIT_CAPACITY);
private final ArrayDeque<UploadedTexture> mBgTextures =
new ArrayDeque<UploadedTexture>(INIT_CAPACITY);
new ArrayDeque<>(INIT_CAPACITY);
private final GLRoot mGLRoot;
private volatile boolean mIsQueued = false;
@@ -47,10 +47,10 @@ public class TiledTexture implements Texture {
private static Tile sFreeTileHead = null;
private static final Object sFreeTileLock = new Object();
private static Bitmap sUploadBitmap;
private static Canvas sCanvas;
private static Paint sBitmapPaint;
private static Paint sPaint;
private static final Bitmap sUploadBitmap;
private static final Canvas sCanvas;
private static final Paint sBitmapPaint;
private static final Paint sPaint;
private int mUploadIndex = 0;
@@ -44,9 +44,9 @@ public abstract class UploadedTexture extends BasicTexture {
// To prevent keeping allocation the borders, we store those used borders here.
// Since the length will be power of two, it won't use too much memory.
private static HashMap<BorderKey, Bitmap> sBorderLines =
private static final HashMap<BorderKey, Bitmap> sBorderLines =
new HashMap<>();
private static BorderKey sBorderKey = new BorderKey();
private static final BorderKey sBorderKey = new BorderKey();
@SuppressWarnings("unused")
private static final String TAG = "Texture";
@@ -25,8 +25,8 @@ import android.support.v4.content.ContextCompat;
public class XmlResourceTexture extends UploadedTexture {
private Context mContext;
private int mResId;
private final Context mContext;
private final int mResId;
private int mWidth;
private int mHeight;
@@ -18,7 +18,7 @@ package com.hippo.gl.util;
import android.graphics.Color;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.AssertError;
public class GalleryUtils {
@@ -51,6 +51,8 @@ public class GalleryUtils {
}
public static void assertInRenderThread() {
AssertUtils.assertEquals("Should not do this in render thread", sCurrentThread, Thread.currentThread());
if (sCurrentThread != Thread.currentThread()) {
throw new AssertError("Should not do this in render thread");
}
}
}
@@ -20,7 +20,6 @@ import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Parcelable;
import android.os.Process;
@@ -40,6 +39,9 @@ import com.hippo.gl.glrenderer.UploadedTexture;
import com.hippo.gl.util.ApiHelper;
import com.hippo.gl.util.GalleryUtils;
import com.hippo.gl.util.MotionEventHelper;
import com.hippo.tuxiang.BestConfigChooser;
import com.hippo.tuxiang.GLSurfaceView;
import com.hippo.tuxiang.Renderer;
import com.hippo.yorozuya.AssertUtils;
import java.util.ArrayDeque;
@@ -47,12 +49,11 @@ import java.util.ArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
// TODO Call attachToRoot and detachFromRoot in render thread
// The root component of all <code>GLView</code>s. The rendering is done in GL
// thread while the event handling is done in the main thread. To synchronize
// the two threads, the entry points of this package need to synchronize on the
@@ -62,7 +63,7 @@ import javax.microedition.khronos.opengles.GL11;
// (2) The public methods of CameraHeadUpDisplay
// (3) The overridden methods in GLRootView.
public class GLRootView extends GLSurfaceView
implements GLSurfaceView.Renderer, GLRoot {
implements GLRoot {
private static final String TAG = "GLRootView";
private static final boolean DEBUG_FPS = false;
@@ -106,22 +107,113 @@ public class GLRootView extends GLSurfaceView
mRenderLock.newCondition();
private boolean mFreeze;
private long mLastDrawFinishTime;
private boolean mInDownState = false;
//private boolean mFirstDraw = true;
private class GLRootRenderer implements Renderer {
/**
* Called when the context is created, possibly after automatic destruction.
*/
@Override
public void onSurfaceCreated(GL10 gl1, EGLConfig config) {
GL11 gl = (GL11) gl1;
if (mGL != null) {
// The GL Object has changed
Log.i(TAG, "GLObject has changed from " + mGL + " to " + gl);
}
mRenderLock.lock();
try {
mGL = gl;
mCanvas = new GLES20Canvas();
BasicTexture.invalidateAllTextures();
} finally {
mRenderLock.unlock();
}
if (DEBUG_FPS) {
setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
} else {
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
}
/**
* Called when the OpenGL surface is recreated without destroying the
* context.
*/
@Override
public void onSurfaceChanged(GL10 gl1, int width, int height) {
Log.i(TAG, "onSurfaceChanged: " + width + "x" + height + ", gl10: " + gl1.toString());
Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY);
GalleryUtils.setRenderThread();
GL11 gl = (GL11) gl1;
AssertUtils.assertTrue(mGL == gl);
mCanvas.setSize(width, height);
}
@Override
public void onDrawFrame(GL10 gl) {
AnimationTime.update();
long t0 = System.nanoTime();
mRenderLock.lock();
while (mFreeze) {
mFreezeCondition.awaitUninterruptibly();
}
try {
onDrawFrameLocked(gl);
} finally {
mRenderLock.unlock();
}
long t = System.nanoTime();
long duration = (t - t0) / 1000000;
if (duration > 34) {
Log.v(TAG, "--- " + duration + " ---");
}
}
@Override
public void onSurfaceDestroyed() {
if (mContentView != null && mContentView.isAttachedToRoot()) {
mContentView.detachFromRoot();
}
}
@Override
public void onPause() {
if (mContentView != null) {
mContentView.pause();
}
}
@Override
public void onResume() {
if (mContentView != null) {
mContentView.resume();
}
}
}
public GLRootView(Context context) {
this(context, null);
}
@SuppressWarnings("deprecation")
public GLRootView(Context context, AttributeSet attrs) {
super(context, attrs);
mFlags |= FLAG_INITIALIZED;
setBackgroundDrawable(null);
setEGLContextClientVersion(2);
setEGLConfigChooser(new BestConfigChooser());
setRenderer(this);
final int eglContextClientVersion = 2;
setEGLContextClientVersion(eglContextClientVersion);
setEGLConfigChooser(new BestConfigChooser(eglContextClientVersion));
setRenderer(new GLRootRenderer());
getHolder().setFormat(PixelFormat.RGB_888);
// Uncomment this to enable gl error check.
@@ -272,49 +364,6 @@ public class GLRootView extends GLSurfaceView
if (changed) requestLayoutContentPane();
}
/**
* Called when the context is created, possibly after automatic destruction.
*/
// This is a GLSurfaceView.Renderer callback
@Override
public void onSurfaceCreated(GL10 gl1, EGLConfig config) {
GL11 gl = (GL11) gl1;
if (mGL != null) {
// The GL Object has changed
Log.i(TAG, "GLObject has changed from " + mGL + " to " + gl);
}
mRenderLock.lock();
try {
mGL = gl;
mCanvas = new GLES20Canvas();
BasicTexture.invalidateAllTextures();
} finally {
mRenderLock.unlock();
}
if (DEBUG_FPS) {
setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
} else {
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
}
/**
* Called when the OpenGL surface is recreated without destroying the
* context.
*/
// This is a GLSurfaceView.Renderer callback
@Override
public void onSurfaceChanged(GL10 gl1, int width, int height) {
Log.i(TAG, "onSurfaceChanged: " + width + "x" + height + ", gl10: " + gl1.toString());
Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY);
GalleryUtils.setRenderThread();
GL11 gl = (GL11) gl1;
AssertUtils.assertTrue(mGL == gl);
mCanvas.setSize(width, height);
}
private void outputFps() {
long now = System.nanoTime();
if (mFrameCountingStart == 0) {
@@ -328,47 +377,6 @@ public class GLRootView extends GLSurfaceView
++mFrameCount;
}
@Override
public void onDrawFrame(GL10 gl) {
AnimationTime.update();
long t0 = System.nanoTime();
mRenderLock.lock();
while (mFreeze) {
mFreezeCondition.awaitUninterruptibly();
}
try {
onDrawFrameLocked(gl);
} finally {
mRenderLock.unlock();
}
// We put a black cover View in front of the SurfaceView and hide it
// after the first draw. This prevents the SurfaceView being transparent
// before the first draw.
//if (mFirstDraw) {
// mFirstDraw = false;
// post(new Runnable() {
// @Override
// public void run() {
// View root = getRootView();
// View cover = root.findViewById(R.id.gl_root_cover);
// cover.setVisibility(GONE);
// }
// });
//}
long t = System.nanoTime();
long duration = (t - t0) / 1000000;
if (duration > 34) {
Log.v(TAG, "--- " + duration + " ---");
}
}
private void onDrawFrameLocked(GL10 gl) {
if (DEBUG_FPS) outputFps();
// release the unbound textures and deleted buffers.
@@ -573,28 +581,18 @@ public class GLRootView extends GLSurfaceView
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
unfreeze();
super.surfaceChanged(holder, format, w, h);
requestLayoutContentPane();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
unfreeze();
super.surfaceCreated(holder);
if (mContentView != null && !mContentView.isAttachedToRoot()) {
mContentView.attachToRoot(this);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
unfreeze();
super.surfaceDestroyed(holder);
if (mContentView != null && mContentView.isAttachedToRoot()) {
mContentView.detachFromRoot();
}
}
@Override
@@ -633,111 +631,4 @@ public class GLRootView extends GLSurfaceView
super.finalize();
}
}
private static abstract class BaseConfigChooser implements EGLConfigChooser {
public BaseConfigChooser(int[] configSpec) {
mConfigSpec = filterConfigSpec(configSpec);
}
@Override
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
int[] num_config = new int[1];
if (!egl.eglChooseConfig(display, mConfigSpec, null, 0,
num_config)) {
throw new IllegalArgumentException("eglChooseConfig failed");
}
int numConfigs = num_config[0];
if (numConfigs <= 0) {
throw new IllegalArgumentException(
"No configs match configSpec");
}
EGLConfig[] configs = new EGLConfig[numConfigs];
if (!egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs,
num_config)) {
throw new IllegalArgumentException("eglChooseConfig#2 failed");
}
EGLConfig config = chooseConfig(egl, display, configs);
if (config == null) {
throw new IllegalArgumentException("No config chosen");
}
return config;
}
abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
EGLConfig[] configs);
protected int[] mConfigSpec;
private int[] filterConfigSpec(int[] configSpec) {
/* We know none of the subclasses define EGL_RENDERABLE_TYPE.
* And we know the configSpec is well formed.
*/
int len = configSpec.length;
int[] newConfigSpec = new int[len + 2];
System.arraycopy(configSpec, 0, newConfigSpec, 0, len-1);
newConfigSpec[len-1] = EGL10.EGL_RENDERABLE_TYPE;
newConfigSpec[len] = 4; // EGL14.EGL_OPENGL_ES2_BIT; /* EGL_OPENGL_ES2_BIT */
newConfigSpec[len+1] = EGL10.EGL_NONE;
return newConfigSpec;
}
}
private static class BestConfigChooser extends BaseConfigChooser {
private final int[] mValue = new int[1];
public BestConfigChooser() {
super(new int[] {
EGL10.EGL_DEPTH_SIZE, 0,
EGL10.EGL_STENCIL_SIZE, 0,
EGL10.EGL_NONE});
}
@Override
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
EGLConfig[] configs) {
// Use score to avoid "No config chosen"
int configIndex = 0;
int maxScore = 0;
for (int i = 0, n = configs.length; i < n; i++) {
EGLConfig config = configs[i];
int redSize = findConfigAttrib(egl, display, config,
EGL10.EGL_RED_SIZE, 0);
int greenSize = findConfigAttrib(egl, display, config,
EGL10.EGL_GREEN_SIZE, 0);
int blueSize = findConfigAttrib(egl, display, config,
EGL10.EGL_BLUE_SIZE, 0);
int alphaSize = findConfigAttrib(egl, display, config,
EGL10.EGL_ALPHA_SIZE, 0);
int sampleBuffers = findConfigAttrib(egl, display, config,
EGL10.EGL_SAMPLE_BUFFERS, 0);
int samples = findConfigAttrib(egl, display, config,
EGL10.EGL_SAMPLES, 0);
int score = redSize + greenSize + blueSize + alphaSize +
sampleBuffers + samples;
if (score > maxScore) {
maxScore = score;
configIndex = i;
}
}
return configs[configIndex];
}
private int findConfigAttrib(EGL10 egl, EGLDisplay display,
EGLConfig config, int attribute, int defaultValue) {
if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
return mValue[0];
}
return defaultValue;
}
}
}
@@ -212,7 +212,7 @@ public class GLView implements TouchOwner {
}
// This should only be called on the content pane (the topmost GLView).
public void attachToRoot(GLRoot root) {
void attachToRoot(GLRoot root) {
AssertUtils.assertTrue(mParent == null && mRoot == null);
onAttachToRoot(root);
}
@@ -223,6 +223,16 @@ public class GLView implements TouchOwner {
onDetachFromRoot();
}
// This should only be called on the content pane (the topmost GLView).
void pause() {
onPause();
}
// This should only be called on the content pane (the topmost GLView).
void resume() {
onResume();
}
public boolean isAttachedToRoot() {
return mRoot != null;
}
@@ -1115,6 +1125,18 @@ public class GLView implements TouchOwner {
mRoot = null;
}
public void onPause() {
for (int i = 0, n = getComponentCount(); i < n; ++i) {
getComponent(i).onPause();
}
}
public void onResume() {
for (int i = 0, n = getComponentCount(); i < n; ++i) {
getComponent(i).onResume();
}
}
public void lockRendering() {
if (mRoot != null) {
mRoot.lockRenderThread();
@@ -20,29 +20,29 @@ import android.graphics.Rect;
import android.text.TextUtils;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.gl.glrenderer.MovableTextTexture;
import com.hippo.gl.glrenderer.ImageMovableTextTexture;
import com.hippo.gl.view.GLView;
import com.hippo.gl.view.Gravity;
import com.hippo.yorozuya.ArrayUtils;
import com.hippo.yorozuya.collect.CollectionUtils;
public class GLMovableTextView extends GLView {
MovableTextTexture mTextTexture;
ImageMovableTextTexture mTextTexture;
private String mText = "";
private int[] mIndexes = ArrayUtils.EMPTY_INT_ARRAY;
private int[] mIndexes = CollectionUtils.EMPTY_INT_ARRAY;
private int mGravity = Gravity.NO_GRAVITY;
private void generateIndexes() {
if (mTextTexture == null || TextUtils.isEmpty(mText)) {
mIndexes = ArrayUtils.EMPTY_INT_ARRAY;
mIndexes = CollectionUtils.EMPTY_INT_ARRAY;
} else {
mIndexes = mTextTexture.getTextIndexes(mText);
}
}
public void setTextTexture(MovableTextTexture textTexture) {
public void setTextTexture(ImageMovableTextTexture textTexture) {
if (mTextTexture == textTexture) {
return;
}
@@ -1,142 +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.image;
import android.graphics.Bitmap;
import java.io.InputStream;
public class Image {
public static final int FORMAT_JPEG = 0x00;
public static final int FORMAT_PNG = 0x01;
public static final int FORMAT_GIF = 0x02;
private long mNativePtr;
private final int mFormat;
private final int mWidth;
private final int mHeight;
private Image(long nativePtr, int format, int width, int height) {
mNativePtr = nativePtr;
mFormat = format;
mWidth = width;
mHeight = height;
}
public int getFormat() {
return mFormat;
}
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
private void checkRecycled() {
if (mNativePtr == 0) {
throw new IllegalStateException("The image is recycled.");
}
}
public boolean complete() {
checkRecycled();
return nativeComplete(mNativePtr, mFormat);
}
public boolean isCompleted() {
checkRecycled();
return nativeIsCompleted(mNativePtr, mFormat);
}
public void render(int srcX, int srcY, Bitmap dst, int dstX, int dstY,
int width, int height, boolean fillBlank, int defaultColor) {
checkRecycled();
nativeRender(mNativePtr, mFormat, srcX, srcY, dst, dstX, dstY,
width, height, fillBlank, defaultColor);
}
public void texImage(boolean init, int tileType, int offsetX, int offsetY) {
checkRecycled();
nativeTexImage(mNativePtr, mFormat, init, tileType, offsetX, offsetY);
}
public void advance() {
checkRecycled();
nativeAdvance(mNativePtr, mFormat);
}
public int getDelay() {
checkRecycled();
return nativeGetDelay(mNativePtr, mFormat);
}
public int getFrameCount() {
checkRecycled();
return nativeFrameCount(mNativePtr, mFormat);
}
public boolean isOpaque() {
checkRecycled();
return nativeIsOpaque(mNativePtr, mFormat);
}
public void recycle() {
if (mNativePtr != 0) {
nativeRecycle(mNativePtr, mFormat);
mNativePtr = 0;
}
}
public boolean isRecycled() {
return mNativePtr == 0;
}
public static Image decode(InputStream is, boolean partially) {
return nativeDecode(is, partially);
}
static {
System.loadLibrary("image");
}
private static native Image nativeDecode(InputStream is, boolean partially);
private static native boolean nativeComplete(long nativePtr, int format);
private static native boolean nativeIsCompleted(long nativePtr, int format);
private static native void nativeRender(long nativePtr, int format,
int srcX, int srcY, Bitmap dst, int dstX, int dstY,
int width, int height, boolean fillBlank, int defaultColor);
private static native void nativeTexImage(long nativePtr, int format,
boolean init, int tileType, int offsetX, int offsetY);
private static native void nativeAdvance(long nativePtr, int format);
private static native int nativeGetDelay(long nativePtr, int format);
private static native int nativeFrameCount(long nativePtr, int format);
private static native boolean nativeIsOpaque(long nativePtr, int format);
private static native void nativeRecycle(long nativePtr, int format);
}
@@ -18,8 +18,8 @@ package com.hippo.io;
import android.support.annotation.NonNull;
import com.hippo.streampipe.InputStreamPipe;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.io.InputStreamPipe;
import java.io.File;
import java.io.FileInputStream;
@@ -28,7 +28,7 @@ import java.io.InputStream;
public class FileInputStreamPipe implements InputStreamPipe {
private File mFile;
private final File mFile;
private InputStream mIs;
public FileInputStreamPipe(File file) {
@@ -18,8 +18,8 @@ package com.hippo.io;
import android.support.annotation.NonNull;
import com.hippo.streampipe.OutputStreamPipe;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.io.OutputStreamPipe;
import java.io.File;
import java.io.FileOutputStream;
@@ -28,7 +28,7 @@ import java.io.OutputStream;
public class FileOutputStreamPipe implements OutputStreamPipe {
private File mFile;
private final File mFile;
private OutputStream mOs;
public FileOutputStreamPipe(File file) {
@@ -18,16 +18,16 @@ package com.hippo.io;
import android.support.annotation.NonNull;
import com.hippo.streampipe.InputStreamPipe;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.io.InputStreamPipe;
import java.io.IOException;
import java.io.InputStream;
public class UniFileInputStreamPipe implements InputStreamPipe {
private UniFile mFile;
private final UniFile mFile;
private InputStream mIs;
public UniFileInputStreamPipe(UniFile file) {
@@ -18,17 +18,16 @@ package com.hippo.io;
import android.support.annotation.NonNull;
import com.hippo.streampipe.OutputStreamPipe;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.io.OutputStreamPipe;
import java.io.IOException;
import java.io.OutputStream;
public class UniFileOutputStreamPipe implements OutputStreamPipe {
private UniFile mUniFile;
private final UniFile mUniFile;
private OutputStream mOs;
public UniFileOutputStreamPipe(UniFile uniFile) {
@@ -25,7 +25,7 @@ import android.support.v4.app.FragmentActivity;
import android.view.View;
import com.hippo.ehviewer.R;
import com.hippo.yorozuya.IntList;
import com.hippo.yorozuya.collect.IntList;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -16,28 +16,27 @@
package com.hippo.text;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.widget.TextView;
import com.hippo.conaco.Conaco;
import com.hippo.conaco.ConacoTask;
import com.hippo.drawable.UnikeryDrawable;
import com.hippo.image.ImageBitmap;
import com.hippo.widget.ObservedTextView;
public class URLImageGetter implements Html.ImageGetter {
private final TextView mTextView;
private final Conaco<Bitmap> mConaco;
private final ObservedTextView mTextView;
private final Conaco<ImageBitmap> mConaco;
public URLImageGetter(TextView textView, Conaco<Bitmap> conaco) {
public URLImageGetter(ObservedTextView textView, Conaco<ImageBitmap> conaco) {
mTextView = textView;
mConaco = conaco;
}
@Override
public Drawable getDrawable(String source) {
UnikeryDrawable drawable = new UnikeryDrawable(mTextView);
mConaco.load(new ConacoTask.Builder<Bitmap>().setUnikery(drawable).setUrl(source).setKey(source));
UnikeryDrawable drawable = new UnikeryDrawable(mTextView, mConaco);
drawable.load(source);
return drawable;
}
}
@@ -22,12 +22,13 @@ import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import com.hippo.streampipe.InputStreamPipe;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.io.InputStreamPipe;
import java.io.IOException;
public class BitmapUtils {
public final class BitmapUtils {
private BitmapUtils() {}
public static Context sContext;
@@ -56,13 +56,4 @@ public final class TextUrl {
return spannable == null ? content : spannable;
}
public static String getFileName(String path) {
if (path == null) {
return path;
}
int start = path.lastIndexOf("/");
return start == -1 ? path : path.substring(start + 1);
}
}
@@ -41,9 +41,9 @@ import com.hippo.util.DrawableManager;
import com.hippo.util.ExceptionUtils;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.IntIdGenerator;
import com.hippo.yorozuya.IntList;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.collect.IntList;
import java.util.ArrayList;
import java.util.List;
@@ -23,9 +23,8 @@ import android.text.Spanned;
import android.text.style.ClickableSpan;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.TextView;
public class LinkifyTextView extends TextView {
public class LinkifyTextView extends ObservedTextView {
private ClickableSpan mCurrentSpan;
@@ -1,5 +1,5 @@
/*
* Copyright 2015 Hippo Seven
* Copyright 2015-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.
@@ -18,32 +18,48 @@ package com.hippo.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import com.hippo.conaco.Conaco;
import com.hippo.conaco.ConacoTask;
import com.hippo.conaco.DataContainer;
import com.hippo.conaco.Unikery;
import com.hippo.conaco.ValueHolder;
import com.hippo.drawable.PreciselyClipDrawable;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.image.ImageBitmap;
import com.hippo.image.ImageDrawable;
import com.hippo.image.RecycledException;
public class LoadImageView extends FixedAspectImageView implements Unikery<Bitmap>,
View.OnClickListener, View.OnLongClickListener {
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class LoadImageView extends FixedAspectImageView implements Unikery<ImageBitmap>,
View.OnClickListener, View.OnLongClickListener, Animatable {
private static final String TAG = LoadImageView.class.getSimpleName();
@IntDef({RETRY_TYPE_NONE, RETRY_TYPE_CLICK, RETRY_TYPE_LONG_CLICK})
@Retention(RetentionPolicy.SOURCE)
private @interface RetryType {}
public static final int RETRY_TYPE_NONE = 0;
public static final int RETRY_TYPE_CLICK = 1;
public static final int RETRY_TYPE_LONG_CLICK = 2;
private int mTaskId = Unikery.INVALID_ID;
private Conaco<Bitmap> mConaco;
private Conaco<ImageBitmap> mConaco;
private String mKey;
private String mUrl;
@@ -55,49 +71,29 @@ public class LoadImageView extends FixedAspectImageView implements Unikery<Bitma
private int mClipWidth = Integer.MIN_VALUE;
private int mClipHeight = Integer.MIN_VALUE;
private ValueHolder<Bitmap> mHolder;
private int mRetryType;
private boolean mFailed;
private RetryType mRetryType = RetryType.NONE;
private static final RetryType[] sRetryTypeArray = {
RetryType.NONE,
RetryType.CLICK,
RetryType.LONG_CLICK
};
public enum RetryType {
NONE (0),
CLICK (1),
LONG_CLICK (2);
RetryType(int ni) {
nativeInt = ni;
}
final int nativeInt;
}
public LoadImageView(Context context) {
super(context);
init(context, null, 0, 0);
}
public LoadImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
init(context, attrs, 0, 0);
}
public LoadImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
public LoadImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle, 0);
}
private void init(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LoadImageView);
final int index = a.getInt(R.styleable.LoadImageView_retryType, -1);
if (index >= 0) {
setRetryType(sRetryTypeArray[index]);
}
@SuppressWarnings("WrongConstant")
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LoadImageView, defStyleAttr, defStyleRes);
setRetryType(a.getInt(R.styleable.LoadImageView_retryType, 0));
a.recycle();
if (!isInEditMode()) {
@@ -105,11 +101,23 @@ public class LoadImageView extends FixedAspectImageView implements Unikery<Bitma
}
}
@Override
public void setTaskId(int id) {
mTaskId = id;
}
@Override
public int getTaskId() {
return mTaskId;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!mFailed) { // Restore if not failed
if (mFailed) {
onFailure();
} else {
load(mKey, mUrl, mContainer, mUseNetwork);
}
}
@@ -117,45 +125,73 @@ public class LoadImageView extends FixedAspectImageView implements Unikery<Bitma
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
// Cancel
mConaco.cancel(this);
// Clear drawable
clearDrawable();
}
public void setRetryType(RetryType retryType) {
if (mRetryType != retryType) {
RetryType oldRetryType = mRetryType;
mRetryType = retryType;
if (mFailed) {
if (oldRetryType == RetryType.CLICK) {
setOnClickListener(null);
setClickable(false);
} else if (oldRetryType == RetryType.LONG_CLICK) {
setOnLongClickListener(null);
setLongClickable(false);
}
if (retryType == RetryType.CLICK) {
setOnClickListener(this);
} else if (retryType == RetryType.LONG_CLICK) {
setOnLongClickListener(this);
}
private ImageDrawable getImageDrawable() {
Drawable drawable = getDrawable();
if (drawable instanceof TransitionDrawable) {
TransitionDrawable transitionDrawable = (TransitionDrawable) drawable;
if (transitionDrawable.getNumberOfLayers() == 2) {
drawable = transitionDrawable.getDrawable(1);
}
}
if (drawable instanceof PreciselyClipDrawable) {
drawable = ((PreciselyClipDrawable) drawable).getWrappedDrawable();
}
if (drawable instanceof ImageDrawable) {
return (ImageDrawable) drawable;
} else {
return null;
}
}
private void cancelRetryType() {
if (mRetryType == RetryType.CLICK) {
private void clearDrawable() {
// Recycle ImageDrawable
ImageDrawable imageDrawable = getImageDrawable();
if (imageDrawable != null) {
imageDrawable.recycle();
}
// Set drawable null
setImageDrawable(null);
}
private void clearRetry() {
if (mRetryType == RETRY_TYPE_CLICK) {
setOnClickListener(null);
setClickable(false);
} else if (mRetryType == RetryType.LONG_CLICK) {
} else if (mRetryType == RETRY_TYPE_LONG_CLICK) {
setOnLongClickListener(null);
setLongClickable(false);
}
}
public void load(String key, String url) {
load(key, url, null, true);
public void setRetryType(@RetryType int retryType) {
if (mRetryType != retryType) {
int oldRetryType = mRetryType;
mRetryType = retryType;
if (mFailed) {
if (oldRetryType == RETRY_TYPE_CLICK) {
setOnClickListener(null);
setClickable(false);
} else if (oldRetryType == RETRY_TYPE_LONG_CLICK) {
setOnLongClickListener(null);
setLongClickable(false);
}
if (retryType == RETRY_TYPE_CLICK) {
setOnClickListener(this);
} else if (retryType == RETRY_TYPE_LONG_CLICK) {
setOnLongClickListener(this);
}
}
}
}
public void setClip(int offsetX, int offsetY, int clipWidth, int clipHeight) {
@@ -172,28 +208,28 @@ public class LoadImageView extends FixedAspectImageView implements Unikery<Bitma
mClipHeight = Integer.MIN_VALUE;
}
public void load(String key, String url) {
load(key, url, null, true);
}
public void load(String key, String url, boolean useNetwork) {
load(key, url, null, useNetwork);
}
public void load(String key, String url, DataContainer container, boolean useNetwork) {
if (url == null || (key == null && container == null)) {
return;
}
mFailed = false;
cancelRetryType();
if (url == null) {
return;
}
if (key == null && container == null) {
return;
}
clearRetry();
mKey = key;
mUrl = url;
mContainer = container;
mUseNetwork = useNetwork;
ConacoTask.Builder<Bitmap> builder = new ConacoTask.Builder<Bitmap>()
ConacoTask.Builder<ImageBitmap> builder = new ConacoTask.Builder<ImageBitmap>()
.setUnikery(this)
.setKey(key)
.setUrl(url)
@@ -217,66 +253,45 @@ public class LoadImageView extends FixedAspectImageView implements Unikery<Bitma
mKey = null;
mUrl = null;
mContainer = null;
removeDrawableAndHolder();
clearDrawable();
}
@Override
public void setTaskId(int id) {
mTaskId = id;
}
@Override
public int getTaskId() {
return mTaskId;
}
private void removeDrawableAndHolder() {
// Remove drawable
setImageDrawable(null);
// Remove holder
if (mHolder != null) {
mHolder.release(this);
mHolder = null;
public void onMiss(int source) {
if (source == Conaco.SOURCE_MEMORY) {
clearDrawable();
}
}
@Override
public void onMiss(Conaco.Source source) {
if (source == Conaco.Source.MEMORY) {
removeDrawableAndHolder();
public void onRequest() {}
@Override
public void onProgress(long singleReceivedSize, long receivedSize, long totalSize) {}
@Override
public void onWait() {
clearDrawable();
}
@Override
public boolean onGetValue(@NonNull ImageBitmap value, int source) {
Drawable drawable;
try {
drawable = new ImageDrawable(value);
} catch (RecycledException e) {
// The image might be recycled because it is removed from memory cache.
Log.d(TAG, "The image is recycled", e);
return false;
}
}
@Override
public void onRequest() {
}
@Override
public void onProgress(long singleReceivedSize, long receivedSize, long totalSize) {
}
@Override
public boolean onGetObject(@NonNull ValueHolder<Bitmap> holder, Conaco.Source source) {
// Release
mKey = null;
mUrl = null;
mContainer = null;
holder.obtain(this);
removeDrawableAndHolder();
mHolder = holder;
Bitmap bitmap = holder.getValue();
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
clearDrawable();
if (Integer.MIN_VALUE != mOffsetX) {
drawable = new PreciselyClipDrawable(drawable, mOffsetX, mOffsetY, mClipWidth, mClipHeight);
}
if ((source == Conaco.Source.DISK || source == Conaco.Source.NETWORK)) {
if ((source == Conaco.SOURCE_DISK || source == Conaco.SOURCE_NETWORK)) {
Drawable[] layers = new Drawable[2];
layers[0] = new ColorDrawable(Color.TRANSPARENT);
layers[1] = drawable;
@@ -290,23 +305,14 @@ public class LoadImageView extends FixedAspectImageView implements Unikery<Bitma
return true;
}
@Override
public void onSetDrawable(Drawable drawable) {
mKey = null;
mUrl = null;
mContainer = null;
removeDrawableAndHolder();
setImageDrawable(drawable);
}
@Override
public void onFailure() {
mFailed = true;
removeDrawableAndHolder();
clearDrawable();
setImageDrawable(getContext().getResources().getDrawable(R.drawable.image_failed));
if (mRetryType == RetryType.CLICK) {
if (mRetryType == RETRY_TYPE_CLICK) {
setOnClickListener(this);
} else if (mRetryType == RetryType.LONG_CLICK) {
} else if (mRetryType == RETRY_TYPE_LONG_CLICK) {
setOnLongClickListener(this);
} else {
// Can't retry, so release
@@ -319,11 +325,32 @@ public class LoadImageView extends FixedAspectImageView implements Unikery<Bitma
@Override
public void onCancel() {
mFailed = false;
cancelRetryType();
// release
mKey = null;
mUrl = null;
mContainer = null;
}
@Override
public void start() {
ImageDrawable drawable = getImageDrawable();
if (drawable != null) {
drawable.start();
}
}
@Override
public void stop() {
ImageDrawable drawable = getImageDrawable();
if (drawable != null) {
drawable.stop();
}
}
@Override
public boolean isRunning() {
ImageDrawable drawable = getImageDrawable();
if (drawable != null) {
return drawable.isRunning();
} else {
return false;
}
}
@Override
@@ -0,0 +1,65 @@
/*
* 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.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class ObservedTextView extends TextView {
private OnWindowAttachListener mOnWindowAttachListener;
public ObservedTextView(Context context) {
super(context);
}
public ObservedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ObservedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mOnWindowAttachListener != null) {
mOnWindowAttachListener.onAttachedToWindow();
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mOnWindowAttachListener != null) {
mOnWindowAttachListener.onDetachedFromWindow();
}
}
public void setOnWindowAttachListener(OnWindowAttachListener onWindowAttachListener) {
mOnWindowAttachListener = onWindowAttachListener;
}
public interface OnWindowAttachListener {
void onAttachedToWindow();
void onDetachedFromWindow();
}
}
-15
View File
@@ -1,15 +0,0 @@
# Copyright 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.
include $(call all-subdir-makefiles)
-23
View File
@@ -1,23 +0,0 @@
# Copyright 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.
APP_ABI := all
APP_PLATFORM := android-14
APP_OPTIM := release
APP_CFLAGS += -ffunction-sections -fdata-sections -fPIC
APP_CPPFLAGS += -ffunction-sections -fdata-sections -fvisibility=hidden -fPIC
APP_LDFLAGS += -Wl,--gc-sections -fPIC
NDK_TOOLCHAIN_VERSION := clang
-26
View File
@@ -1,26 +0,0 @@
# Copyright 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.
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := gif
LOCAL_SRC_FILES := \
dgif_lib.c \
gif_hash.c \
gifalloc.c \
openbsd-reallocarray.c
include $(BUILD_STATIC_LIBRARY)
File diff suppressed because it is too large. Load diff
-132
View File
@@ -1,132 +0,0 @@
/*****************************************************************************
gif_hash.c -- module to support the following operations:
1. InitHashTable - initialize hash table.
2. ClearHashTable - clear the hash table to an empty state.
2. InsertHashTable - insert one item into data structure.
3. ExistsHashTable - test if item exists in data structure.
This module is used to hash the GIF codes during encoding.
*****************************************************************************/
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include "gif_lib.h"
#include "gif_hash.h"
#include "gif_lib_private.h"
/* #define DEBUG_HIT_RATE Debug number of misses per hash Insert/Exists. */
#ifdef DEBUG_HIT_RATE
static long NumberOfTests = 0,
NumberOfMisses = 0;
#endif /* DEBUG_HIT_RATE */
static int KeyItem(uint32_t Item);
/******************************************************************************
Initialize HashTable - allocate the memory needed and clear it. *
******************************************************************************/
GifHashTableType *_InitHashTable(void)
{
GifHashTableType *HashTable;
if ((HashTable = (GifHashTableType *) malloc(sizeof(GifHashTableType)))
== NULL)
return NULL;
_ClearHashTable(HashTable);
return HashTable;
}
/******************************************************************************
Routine to clear the HashTable to an empty state. *
This part is a little machine depended. Use the commented part otherwise. *
******************************************************************************/
void _ClearHashTable(GifHashTableType *HashTable)
{
memset(HashTable -> HTable, 0xFF, HT_SIZE * sizeof(uint32_t));
}
/******************************************************************************
Routine to insert a new Item into the HashTable. The data is assumed to be *
new one. *
******************************************************************************/
void _InsertHashTable(GifHashTableType *HashTable, uint32_t Key, int Code)
{
int HKey = KeyItem(Key);
uint32_t *HTable = HashTable -> HTable;
#ifdef DEBUG_HIT_RATE
NumberOfTests++;
NumberOfMisses++;
#endif /* DEBUG_HIT_RATE */
while (HT_GET_KEY(HTable[HKey]) != 0xFFFFFL) {
#ifdef DEBUG_HIT_RATE
NumberOfMisses++;
#endif /* DEBUG_HIT_RATE */
HKey = (HKey + 1) & HT_KEY_MASK;
}
HTable[HKey] = HT_PUT_KEY(Key) | HT_PUT_CODE(Code);
}
/******************************************************************************
Routine to test if given Key exists in HashTable and if so returns its code *
Returns the Code if key was found, -1 if not. *
******************************************************************************/
int _ExistsHashTable(GifHashTableType *HashTable, uint32_t Key)
{
int HKey = KeyItem(Key);
uint32_t *HTable = HashTable -> HTable, HTKey;
#ifdef DEBUG_HIT_RATE
NumberOfTests++;
NumberOfMisses++;
#endif /* DEBUG_HIT_RATE */
while ((HTKey = HT_GET_KEY(HTable[HKey])) != 0xFFFFFL) {
#ifdef DEBUG_HIT_RATE
NumberOfMisses++;
#endif /* DEBUG_HIT_RATE */
if (Key == HTKey) return HT_GET_CODE(HTable[HKey]);
HKey = (HKey + 1) & HT_KEY_MASK;
}
return -1;
}
/******************************************************************************
Routine to generate an HKey for the hashtable out of the given unique key. *
The given Key is assumed to be 20 bits as follows: lower 8 bits are the *
new postfix character, while the upper 12 bits are the prefix code. *
Because the average hit ratio is only 2 (2 hash references per entry), *
evaluating more complex keys (such as twin prime keys) does not worth it! *
******************************************************************************/
static int KeyItem(uint32_t Item)
{
return ((Item >> 12) ^ Item) & HT_KEY_MASK;
}
#ifdef DEBUG_HIT_RATE
/******************************************************************************
Debugging routine to print the hit ratio - number of times the hash table *
was tested per operation. This routine was used to test the KeyItem routine *
******************************************************************************/
void HashTablePrintHitRatio(void)
{
printf("Hash Table Hit Ratio is %ld/%ld = %ld%%.\n",
NumberOfMisses, NumberOfTests,
NumberOfMisses * 100 / NumberOfTests);
}
#endif /* DEBUG_HIT_RATE */
/* end */
-39
View File
@@ -1,39 +0,0 @@
/******************************************************************************
gif_hash.h - magfic constants and declarations for GIF LZW
******************************************************************************/
#ifndef _GIF_HASH_H_
#define _GIF_HASH_H_
#include <unistd.h>
#include <stdint.h>
#define HT_SIZE 8192 /* 12bits = 4096 or twice as big! */
#define HT_KEY_MASK 0x1FFF /* 13bits keys */
#define HT_KEY_NUM_BITS 13 /* 13bits keys */
#define HT_MAX_KEY 8191 /* 13bits - 1, maximal code possible */
#define HT_MAX_CODE 4095 /* Biggest code possible in 12 bits. */
/* The 32 bits of the long are divided into two parts for the key & code: */
/* 1. The code is 12 bits as our compression algorithm is limited to 12bits */
/* 2. The key is 12 bits Prefix code + 8 bit new char or 20 bits. */
/* The key is the upper 20 bits. The code is the lower 12. */
#define HT_GET_KEY(l) (l >> 12)
#define HT_GET_CODE(l) (l & 0x0FFF)
#define HT_PUT_KEY(l) (l << 12)
#define HT_PUT_CODE(l) (l & 0x0FFF)
typedef struct GifHashTableType {
uint32_t HTable[HT_SIZE];
} GifHashTableType;
GifHashTableType *_InitHashTable(void);
void _ClearHashTable(GifHashTableType *HashTable);
void _InsertHashTable(GifHashTableType *HashTable, uint32_t Key, int Code);
int _ExistsHashTable(GifHashTableType *HashTable, uint32_t Key);
#endif /* _GIF_HASH_H_ */
/* end */
-313
View File
@@ -1,313 +0,0 @@
/******************************************************************************
gif_lib.h - service library for decoding and encoding GIF images
*****************************************************************************/
#ifndef _GIF_LIB_H_
#define _GIF_LIB_H_ 1
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define GIFLIB_MAJOR 5
#define GIFLIB_MINOR 1
#define GIFLIB_RELEASE 4
#define GIF_ERROR 0
#define GIF_OK 1
#include <stddef.h>
#include <stdbool.h>
#define GIF_STAMP "GIFVER" /* First chars in file - GIF stamp. */
#define GIF_STAMP_LEN sizeof(GIF_STAMP) - 1
#define GIF_VERSION_POS 3 /* Version first character in stamp. */
#define GIF87_STAMP "GIF87a" /* First chars in file - GIF stamp. */
#define GIF89_STAMP "GIF89a" /* First chars in file - GIF stamp. */
typedef unsigned char GifPixelType;
typedef unsigned char *GifRowType;
typedef unsigned char GifByteType;
typedef unsigned int GifPrefixType;
typedef int GifWord;
typedef struct GifColorType {
GifByteType Red, Green, Blue;
} GifColorType;
typedef struct ColorMapObject {
int ColorCount;
int BitsPerPixel;
bool SortFlag;
GifColorType *Colors; /* on malloc(3) heap */
} ColorMapObject;
typedef struct GifImageDesc {
GifWord Left, Top, Width, Height; /* Current image dimensions. */
bool Interlace; /* Sequential/Interlaced lines. */
ColorMapObject *ColorMap; /* The local color map */
} GifImageDesc;
typedef struct ExtensionBlock {
int ByteCount;
GifByteType *Bytes; /* on malloc(3) heap */
int Function; /* The block function code */
#define CONTINUE_EXT_FUNC_CODE 0x00 /* continuation subblock */
#define COMMENT_EXT_FUNC_CODE 0xfe /* comment */
#define GRAPHICS_EXT_FUNC_CODE 0xf9 /* graphics control (GIF89) */
#define PLAINTEXT_EXT_FUNC_CODE 0x01 /* plaintext */
#define APPLICATION_EXT_FUNC_CODE 0xff /* application block */
} ExtensionBlock;
typedef struct SavedImage {
GifImageDesc ImageDesc;
GifByteType *RasterBits; /* on malloc(3) heap */
int ExtensionBlockCount; /* Count of extensions before image */
ExtensionBlock *ExtensionBlocks; /* Extensions before image */
} SavedImage;
typedef struct GifFileType {
GifWord SWidth, SHeight; /* Size of virtual canvas */
GifWord SColorResolution; /* How many colors can we generate? */
GifWord SBackGroundColor; /* Background color for virtual canvas */
GifByteType AspectByte; /* Used to compute pixel aspect ratio */
ColorMapObject *SColorMap; /* Global colormap, NULL if nonexistent. */
int ImageCount; /* Number of current image (both APIs) */
GifImageDesc Image; /* Current image (low-level API) */
SavedImage *SavedImages; /* Image sequence (high-level API) */
int ExtensionBlockCount; /* Count extensions past last image */
ExtensionBlock *ExtensionBlocks; /* Extensions past last image */
int Error; /* Last error condition reported */
void *UserData; /* hook to attach user data (TVT) */
void *Private; /* Don't mess with this! */
} GifFileType;
#define GIF_ASPECT_RATIO(n) ((n)+15.0/64.0)
typedef enum {
UNDEFINED_RECORD_TYPE,
SCREEN_DESC_RECORD_TYPE,
IMAGE_DESC_RECORD_TYPE, /* Begin with ',' */
EXTENSION_RECORD_TYPE, /* Begin with '!' */
TERMINATE_RECORD_TYPE /* Begin with ';' */
} GifRecordType;
/* func type to read gif data from arbitrary sources (TVT) */
typedef int (*InputFunc) (GifFileType *, GifByteType *, int);
/* func type to write gif data to arbitrary targets.
* Returns count of bytes written. (MRB)
*/
typedef int (*OutputFunc) (GifFileType *, const GifByteType *, int);
/******************************************************************************
GIF89 structures
******************************************************************************/
typedef struct GraphicsControlBlock {
int DisposalMode;
#define DISPOSAL_UNSPECIFIED 0 /* No disposal specified. */
#define DISPOSE_DO_NOT 1 /* Leave image in place */
#define DISPOSE_BACKGROUND 2 /* Set area too background color */
#define DISPOSE_PREVIOUS 3 /* Restore to previous content */
bool UserInputFlag; /* User confirmation required before disposal */
int DelayTime; /* pre-display delay in 0.01sec units */
int TransparentColor; /* Palette index for transparency, -1 if none */
#define NO_TRANSPARENT_COLOR -1
} GraphicsControlBlock;
/******************************************************************************
GIF encoding routines
******************************************************************************/
/* Main entry points */
GifFileType *EGifOpenFileName(const char *GifFileName,
const bool GifTestExistence, int *Error);
GifFileType *EGifOpenFileHandle(const int GifFileHandle, int *Error);
GifFileType *EGifOpen(void *userPtr, OutputFunc writeFunc, int *Error);
int EGifSpew(GifFileType * GifFile);
const char *EGifGetGifVersion(GifFileType *GifFile); /* new in 5.x */
int EGifCloseFile(GifFileType *GifFile, int *ErrorCode);
#define E_GIF_SUCCEEDED 0
#define E_GIF_ERR_OPEN_FAILED 1 /* And EGif possible errors. */
#define E_GIF_ERR_WRITE_FAILED 2
#define E_GIF_ERR_HAS_SCRN_DSCR 3
#define E_GIF_ERR_HAS_IMAG_DSCR 4
#define E_GIF_ERR_NO_COLOR_MAP 5
#define E_GIF_ERR_DATA_TOO_BIG 6
#define E_GIF_ERR_NOT_ENOUGH_MEM 7
#define E_GIF_ERR_DISK_IS_FULL 8
#define E_GIF_ERR_CLOSE_FAILED 9
#define E_GIF_ERR_NOT_WRITEABLE 10
/* These are legacy. You probably do not want to call them directly */
int EGifPutScreenDesc(GifFileType *GifFile,
const int GifWidth, const int GifHeight,
const int GifColorRes,
const int GifBackGround,
const ColorMapObject *GifColorMap);
int EGifPutImageDesc(GifFileType *GifFile,
const int GifLeft, const int GifTop,
const int GifWidth, const int GifHeight,
const bool GifInterlace,
const ColorMapObject *GifColorMap);
void EGifSetGifVersion(GifFileType *GifFile, const bool gif89);
int EGifPutLine(GifFileType *GifFile, GifPixelType *GifLine,
int GifLineLen);
int EGifPutPixel(GifFileType *GifFile, const GifPixelType GifPixel);
int EGifPutComment(GifFileType *GifFile, const char *GifComment);
int EGifPutExtensionLeader(GifFileType *GifFile, const int GifExtCode);
int EGifPutExtensionBlock(GifFileType *GifFile,
const int GifExtLen, const void *GifExtension);
int EGifPutExtensionTrailer(GifFileType *GifFile);
int EGifPutExtension(GifFileType *GifFile, const int GifExtCode,
const int GifExtLen,
const void *GifExtension);
int EGifPutCode(GifFileType *GifFile, int GifCodeSize,
const GifByteType *GifCodeBlock);
int EGifPutCodeNext(GifFileType *GifFile,
const GifByteType *GifCodeBlock);
/******************************************************************************
GIF decoding routines
******************************************************************************/
/* Main entry points */
GifFileType *DGifOpenFileName(const char *GifFileName, int *Error);
GifFileType *DGifOpenFileHandle(int GifFileHandle, int *Error);
int DGifSlurp(GifFileType * GifFile);
int DGifGlance(GifFileType * GifFile);
GifFileType *DGifOpen(void *userPtr, InputFunc readFunc, int *Error); /* new one (TVT) */
int DGifCloseFile(GifFileType * GifFile, int *ErrorCode);
#define D_GIF_SUCCEEDED 0
#define D_GIF_ERR_OPEN_FAILED 101 /* And DGif possible errors. */
#define D_GIF_ERR_READ_FAILED 102
#define D_GIF_ERR_NOT_GIF_FILE 103
#define D_GIF_ERR_NO_SCRN_DSCR 104
#define D_GIF_ERR_NO_IMAG_DSCR 105
#define D_GIF_ERR_NO_COLOR_MAP 106
#define D_GIF_ERR_WRONG_RECORD 107
#define D_GIF_ERR_DATA_TOO_BIG 108
#define D_GIF_ERR_NOT_ENOUGH_MEM 109
#define D_GIF_ERR_CLOSE_FAILED 110
#define D_GIF_ERR_NOT_READABLE 111
#define D_GIF_ERR_IMAGE_DEFECT 112
#define D_GIF_ERR_EOF_TOO_SOON 113
/* These are legacy. You probably do not want to call them directly */
int DGifGetScreenDesc(GifFileType *GifFile);
int DGifGetRecordType(GifFileType *GifFile, GifRecordType *GifType);
int DGifGetImageDesc(GifFileType *GifFile);
int DGifGetLine(GifFileType *GifFile, GifPixelType *GifLine, int GifLineLen);
int DGifGetPixel(GifFileType *GifFile, GifPixelType GifPixel);
int DGifGetComment(GifFileType *GifFile, char *GifComment);
int DGifGetExtension(GifFileType *GifFile, int *GifExtCode,
GifByteType **GifExtension);
int DGifGetExtensionNext(GifFileType *GifFile, GifByteType **GifExtension);
int DGifGetCode(GifFileType *GifFile, int *GifCodeSize,
GifByteType **GifCodeBlock);
int DGifGetCodeNext(GifFileType *GifFile, GifByteType **GifCodeBlock);
int DGifGetLZCodes(GifFileType *GifFile, int *GifCode);
/******************************************************************************
Color table quantization (deprecated)
******************************************************************************/
int GifQuantizeBuffer(unsigned int Width, unsigned int Height,
int *ColorMapSize, GifByteType * RedInput,
GifByteType * GreenInput, GifByteType * BlueInput,
GifByteType * OutputBuffer,
GifColorType * OutputColorMap);
/******************************************************************************
Error handling and reporting.
******************************************************************************/
extern const char *GifErrorString(int ErrorCode); /* new in 2012 - ESR */
/*****************************************************************************
Everything below this point is new after version 1.2, supporting `slurp
mode' for doing I/O in two big belts with all the image-bashing in core.
******************************************************************************/
/******************************************************************************
Color map handling from gif_alloc.c
******************************************************************************/
extern ColorMapObject *GifMakeMapObject(int ColorCount,
const GifColorType *ColorMap);
extern void GifFreeMapObject(ColorMapObject *Object);
extern ColorMapObject *GifUnionColorMap(const ColorMapObject *ColorIn1,
const ColorMapObject *ColorIn2,
GifPixelType ColorTransIn2[]);
extern int GifBitSize(int n);
extern void *
reallocarray(void *optr, size_t nmemb, size_t size);
/******************************************************************************
Support for the in-core structures allocation (slurp mode).
******************************************************************************/
extern void GifApplyTranslation(SavedImage *Image, GifPixelType Translation[]);
extern int GifAddExtensionBlock(int *ExtensionBlock_Count,
ExtensionBlock **ExtensionBlocks,
int Function,
unsigned int Len, unsigned char ExtData[]);
extern void GifFreeExtensions(int *ExtensionBlock_Count,
ExtensionBlock **ExtensionBlocks);
extern SavedImage *GifMakeSavedImage(GifFileType *GifFile,
const SavedImage *CopyFrom);
extern void GifFreeSavedImages(GifFileType *GifFile);
/******************************************************************************
5.x functions for GIF89 graphics control blocks
******************************************************************************/
int DGifExtensionToGCB(const size_t GifExtensionLength,
const GifByteType *GifExtension,
GraphicsControlBlock *GCB);
size_t EGifGCBToExtension(const GraphicsControlBlock *GCB,
GifByteType *GifExtension);
int DGifSavedExtensionToGCB(GifFileType *GifFile,
int ImageIndex,
GraphicsControlBlock *GCB);
int EGifGCBToSavedExtension(const GraphicsControlBlock *GCB,
GifFileType *GifFile,
int ImageIndex);
/******************************************************************************
The library's internal utility font
******************************************************************************/
#define GIF_FONT_WIDTH 8
#define GIF_FONT_HEIGHT 8
extern const unsigned char GifAsciiTable8x8[][GIF_FONT_WIDTH];
extern void GifDrawText8x8(SavedImage *Image,
const int x, const int y,
const char *legend, const int color);
extern void GifDrawBox(SavedImage *Image,
const int x, const int y,
const int w, const int d, const int color);
extern void GifDrawRectangle(SavedImage *Image,
const int x, const int y,
const int w, const int d, const int color);
extern void GifDrawBoxedText8x8(SavedImage *Image,
const int x, const int y,
const char *legend,
const int border, const int bg, const int fg);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* _GIF_LIB_H */
/* end */
-64
View File
@@ -1,64 +0,0 @@
/****************************************************************************
gif_lib_private.h - internal giflib routines and structures
****************************************************************************/
#ifndef _GIF_LIB_PRIVATE_H
#define _GIF_LIB_PRIVATE_H
#include "gif_lib.h"
#include "gif_hash.h"
#if !defined(S_IREAD) && defined(S_IRUSR)
# define S_IREAD S_IRUSR
# define S_IWRITE S_IRUSR
#endif
#define EXTENSION_INTRODUCER 0x21
#define DESCRIPTOR_INTRODUCER 0x2c
#define TERMINATOR_INTRODUCER 0x3b
#define LZ_MAX_CODE 4095 /* Biggest code possible in 12 bits. */
#define LZ_BITS 12
#define FLUSH_OUTPUT 4096 /* Impossible code, to signal flush. */
#define FIRST_CODE 4097 /* Impossible code, to signal first. */
#define NO_SUCH_CODE 4098 /* Impossible code, to signal empty. */
#define FILE_STATE_WRITE 0x01
#define FILE_STATE_SCREEN 0x02
#define FILE_STATE_IMAGE 0x04
#define FILE_STATE_READ 0x08
#define IS_READABLE(Private) (Private->FileState & FILE_STATE_READ)
#define IS_WRITEABLE(Private) (Private->FileState & FILE_STATE_WRITE)
typedef struct GifFilePrivateType {
GifWord FileState, FileHandle, /* Where all this data goes to! */
BitsPerPixel, /* Bits per pixel (Codes uses at least this + 1). */
ClearCode, /* The CLEAR LZ code. */
EOFCode, /* The EOF LZ code. */
RunningCode, /* The next code algorithm can generate. */
RunningBits, /* The number of bits required to represent RunningCode. */
MaxCode1, /* 1 bigger than max. possible code, in RunningBits bits. */
LastCode, /* The code before the current code. */
CrntCode, /* Current algorithm code. */
StackPtr, /* For character stack (see below). */
CrntShiftState; /* Number of bits in CrntShiftDWord. */
unsigned long CrntShiftDWord; /* For bytes decomposition into codes. */
unsigned long PixelCount; /* Number of pixels in image. */
FILE *File; /* File as stream. */
InputFunc Read; /* function to read gif input (TVT) */
OutputFunc Write; /* function to write gif output (MRB) */
GifByteType Buf[256]; /* Compressed input is buffered here. */
GifByteType Stack[LZ_MAX_CODE]; /* Decoded pixels are stacked here. */
GifByteType Suffix[LZ_MAX_CODE + 1]; /* So we can trace the codes. */
GifPrefixType Prefix[LZ_MAX_CODE + 1];
GifHashTableType *HashTable;
bool gif89;
} GifFilePrivateType;
#endif /* _GIF_LIB_PRIVATE_H */
/* end */
-412
View File
@@ -1,412 +0,0 @@
/*****************************************************************************
GIF construction tools
****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "gif_lib.h"
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
/******************************************************************************
Miscellaneous utility functions
******************************************************************************/
/* return smallest bitfield size n will fit in */
int
GifBitSize(int n)
{
register int i;
for (i = 1; i <= 8; i++)
if ((1 << i) >= n)
break;
return (i);
}
/******************************************************************************
Color map object functions
******************************************************************************/
/*
* Allocate a color map of given size; initialize with contents of
* ColorMap if that pointer is non-NULL.
*/
ColorMapObject *
GifMakeMapObject(int ColorCount, const GifColorType *ColorMap)
{
ColorMapObject *Object;
/*** FIXME: Our ColorCount has to be a power of two. Is it necessary to
* make the user know that or should we automatically round up instead? */
if (ColorCount != (1 << GifBitSize(ColorCount))) {
return ((ColorMapObject *) NULL);
}
Object = (ColorMapObject *)malloc(sizeof(ColorMapObject));
if (Object == (ColorMapObject *) NULL) {
return ((ColorMapObject *) NULL);
}
Object->Colors = (GifColorType *)calloc(ColorCount, sizeof(GifColorType));
if (Object->Colors == (GifColorType *) NULL) {
free(Object);
return ((ColorMapObject *) NULL);
}
Object->ColorCount = ColorCount;
Object->BitsPerPixel = GifBitSize(ColorCount);
Object->SortFlag = false;
if (ColorMap != NULL) {
memcpy((char *)Object->Colors,
(char *)ColorMap, ColorCount * sizeof(GifColorType));
}
return (Object);
}
/*******************************************************************************
Free a color map object
*******************************************************************************/
void
GifFreeMapObject(ColorMapObject *Object)
{
if (Object != NULL) {
(void)free(Object->Colors);
(void)free(Object);
}
}
#ifdef DEBUG
void
DumpColorMap(ColorMapObject *Object,
FILE * fp)
{
if (Object != NULL) {
int i, j, Len = Object->ColorCount;
for (i = 0; i < Len; i += 4) {
for (j = 0; j < 4 && j < Len; j++) {
(void)fprintf(fp, "%3d: %02x %02x %02x ", i + j,
Object->Colors[i + j].Red,
Object->Colors[i + j].Green,
Object->Colors[i + j].Blue);
}
(void)fprintf(fp, "\n");
}
}
}
#endif /* DEBUG */
/*******************************************************************************
Compute the union of two given color maps and return it. If result can't
fit into 256 colors, NULL is returned, the allocated union otherwise.
ColorIn1 is copied as is to ColorUnion, while colors from ColorIn2 are
copied iff they didn't exist before. ColorTransIn2 maps the old
ColorIn2 into the ColorUnion color map table./
*******************************************************************************/
ColorMapObject *
GifUnionColorMap(const ColorMapObject *ColorIn1,
const ColorMapObject *ColorIn2,
GifPixelType ColorTransIn2[])
{
int i, j, CrntSlot, RoundUpTo, NewGifBitSize;
ColorMapObject *ColorUnion;
/*
* We don't worry about duplicates within either color map; if
* the caller wants to resolve those, he can perform unions
* with an empty color map.
*/
/* Allocate table which will hold the result for sure. */
ColorUnion = GifMakeMapObject(MAX(ColorIn1->ColorCount,
ColorIn2->ColorCount) * 2, NULL);
if (ColorUnion == NULL)
return (NULL);
/*
* Copy ColorIn1 to ColorUnion.
*/
for (i = 0; i < ColorIn1->ColorCount; i++)
ColorUnion->Colors[i] = ColorIn1->Colors[i];
CrntSlot = ColorIn1->ColorCount;
/*
* Potentially obnoxious hack:
*
* Back CrntSlot down past all contiguous {0, 0, 0} slots at the end
* of table 1. This is very useful if your display is limited to
* 16 colors.
*/
while (ColorIn1->Colors[CrntSlot - 1].Red == 0
&& ColorIn1->Colors[CrntSlot - 1].Green == 0
&& ColorIn1->Colors[CrntSlot - 1].Blue == 0)
CrntSlot--;
/* Copy ColorIn2 to ColorUnion (use old colors if they exist): */
for (i = 0; i < ColorIn2->ColorCount && CrntSlot <= 256; i++) {
/* Let's see if this color already exists: */
for (j = 0; j < ColorIn1->ColorCount; j++)
if (memcmp (&ColorIn1->Colors[j], &ColorIn2->Colors[i],
sizeof(GifColorType)) == 0)
break;
if (j < ColorIn1->ColorCount)
ColorTransIn2[i] = j; /* color exists in Color1 */
else {
/* Color is new - copy it to a new slot: */
ColorUnion->Colors[CrntSlot] = ColorIn2->Colors[i];
ColorTransIn2[i] = CrntSlot++;
}
}
if (CrntSlot > 256) {
GifFreeMapObject(ColorUnion);
return ((ColorMapObject *) NULL);
}
NewGifBitSize = GifBitSize(CrntSlot);
RoundUpTo = (1 << NewGifBitSize);
if (RoundUpTo != ColorUnion->ColorCount) {
register GifColorType *Map = ColorUnion->Colors;
/*
* Zero out slots up to next power of 2.
* We know these slots exist because of the way ColorUnion's
* start dimension was computed.
*/
for (j = CrntSlot; j < RoundUpTo; j++)
Map[j].Red = Map[j].Green = Map[j].Blue = 0;
/* perhaps we can shrink the map? */
if (RoundUpTo < ColorUnion->ColorCount) {
GifColorType *new_map = (GifColorType *)reallocarray(Map,
RoundUpTo, sizeof(GifColorType));
if( new_map == NULL ) {
GifFreeMapObject(ColorUnion);
return ((ColorMapObject *) NULL);
}
ColorUnion->Colors = new_map;
}
}
ColorUnion->ColorCount = RoundUpTo;
ColorUnion->BitsPerPixel = NewGifBitSize;
return (ColorUnion);
}
/*******************************************************************************
Apply a given color translation to the raster bits of an image
*******************************************************************************/
void
GifApplyTranslation(SavedImage *Image, GifPixelType Translation[])
{
register int i;
register int RasterSize = Image->ImageDesc.Height * Image->ImageDesc.Width;
for (i = 0; i < RasterSize; i++)
Image->RasterBits[i] = Translation[Image->RasterBits[i]];
}
/******************************************************************************
Extension record functions
******************************************************************************/
int
GifAddExtensionBlock(int *ExtensionBlockCount,
ExtensionBlock **ExtensionBlocks,
int Function,
unsigned int Len,
unsigned char ExtData[])
{
ExtensionBlock *ep;
if (*ExtensionBlocks == NULL)
*ExtensionBlocks=(ExtensionBlock *)malloc(sizeof(ExtensionBlock));
else {
ExtensionBlock* ep_new = (ExtensionBlock *)reallocarray
(*ExtensionBlocks, (*ExtensionBlockCount + 1),
sizeof(ExtensionBlock));
if( ep_new == NULL )
return (GIF_ERROR);
*ExtensionBlocks = ep_new;
}
if (*ExtensionBlocks == NULL)
return (GIF_ERROR);
ep = &(*ExtensionBlocks)[(*ExtensionBlockCount)++];
ep->Function = Function;
ep->ByteCount=Len;
ep->Bytes = (GifByteType *)malloc(ep->ByteCount);
if (ep->Bytes == NULL)
return (GIF_ERROR);
if (ExtData != NULL) {
memcpy(ep->Bytes, ExtData, Len);
}
return (GIF_OK);
}
void
GifFreeExtensions(int *ExtensionBlockCount,
ExtensionBlock **ExtensionBlocks)
{
ExtensionBlock *ep;
if (*ExtensionBlocks == NULL)
return;
for (ep = *ExtensionBlocks;
ep < (*ExtensionBlocks + *ExtensionBlockCount);
ep++)
(void)free((char *)ep->Bytes);
(void)free((char *)*ExtensionBlocks);
*ExtensionBlocks = NULL;
*ExtensionBlockCount = 0;
}
/******************************************************************************
Image block allocation functions
******************************************************************************/
/* Private Function:
* Frees the last image in the GifFile->SavedImages array
*/
void
FreeLastSavedImage(GifFileType *GifFile)
{
SavedImage *sp;
if ((GifFile == NULL) || (GifFile->SavedImages == NULL))
return;
/* Remove one SavedImage from the GifFile */
GifFile->ImageCount--;
sp = &GifFile->SavedImages[GifFile->ImageCount];
/* Deallocate its Colormap */
if (sp->ImageDesc.ColorMap != NULL) {
GifFreeMapObject(sp->ImageDesc.ColorMap);
sp->ImageDesc.ColorMap = NULL;
}
/* Deallocate the image data */
if (sp->RasterBits != NULL)
free((char *)sp->RasterBits);
/* Deallocate any extensions */
GifFreeExtensions(&sp->ExtensionBlockCount, &sp->ExtensionBlocks);
/*** FIXME: We could realloc the GifFile->SavedImages structure but is
* there a point to it? Saves some memory but we'd have to do it every
* time. If this is used in GifFreeSavedImages then it would be inefficient
* (The whole array is going to be deallocated.) If we just use it when
* we want to free the last Image it's convenient to do it here.
*/
}
/*
* Append an image block to the SavedImages array
*/
SavedImage *
GifMakeSavedImage(GifFileType *GifFile, const SavedImage *CopyFrom)
{
if (GifFile->SavedImages == NULL)
GifFile->SavedImages = (SavedImage *)malloc(sizeof(SavedImage));
else
GifFile->SavedImages = (SavedImage *)reallocarray(GifFile->SavedImages,
(GifFile->ImageCount + 1), sizeof(SavedImage));
if (GifFile->SavedImages == NULL)
return ((SavedImage *)NULL);
else {
SavedImage *sp = &GifFile->SavedImages[GifFile->ImageCount++];
memset((char *)sp, '\0', sizeof(SavedImage));
if (CopyFrom != NULL) {
memcpy((char *)sp, CopyFrom, sizeof(SavedImage));
/*
* Make our own allocated copies of the heap fields in the
* copied record. This guards against potential aliasing
* problems.
*/
/* first, the local color map */
if (sp->ImageDesc.ColorMap != NULL) {
sp->ImageDesc.ColorMap = GifMakeMapObject(
CopyFrom->ImageDesc.ColorMap->ColorCount,
CopyFrom->ImageDesc.ColorMap->Colors);
if (sp->ImageDesc.ColorMap == NULL) {
FreeLastSavedImage(GifFile);
return (SavedImage *)(NULL);
}
}
/* next, the raster */
sp->RasterBits = (unsigned char *)reallocarray(NULL,
(CopyFrom->ImageDesc.Height *
CopyFrom->ImageDesc.Width),
sizeof(GifPixelType));
if (sp->RasterBits == NULL) {
FreeLastSavedImage(GifFile);
return (SavedImage *)(NULL);
}
memcpy(sp->RasterBits, CopyFrom->RasterBits,
sizeof(GifPixelType) * CopyFrom->ImageDesc.Height *
CopyFrom->ImageDesc.Width);
/* finally, the extension blocks */
if (sp->ExtensionBlocks != NULL) {
sp->ExtensionBlocks = (ExtensionBlock *)reallocarray(NULL,
CopyFrom->ExtensionBlockCount,
sizeof(ExtensionBlock));
if (sp->ExtensionBlocks == NULL) {
FreeLastSavedImage(GifFile);
return (SavedImage *)(NULL);
}
memcpy(sp->ExtensionBlocks, CopyFrom->ExtensionBlocks,
sizeof(ExtensionBlock) * CopyFrom->ExtensionBlockCount);
}
}
return (sp);
}
}
void
GifFreeSavedImages(GifFileType *GifFile)
{
SavedImage *sp;
if ((GifFile == NULL) || (GifFile->SavedImages == NULL)) {
return;
}
for (sp = GifFile->SavedImages;
sp < GifFile->SavedImages + GifFile->ImageCount; sp++) {
if (sp->ImageDesc.ColorMap != NULL) {
GifFreeMapObject(sp->ImageDesc.ColorMap);
sp->ImageDesc.ColorMap = NULL;
}
if (sp->RasterBits != NULL)
free((char *)sp->RasterBits);
GifFreeExtensions(&sp->ExtensionBlockCount, &sp->ExtensionBlocks);
}
free((char *)GifFile->SavedImages);
GifFile->SavedImages = NULL;
}
/* end */
@@ -1,39 +0,0 @@
/* $OpenBSD: reallocarray.c,v 1.1 2014/05/08 21:43:49 deraadt Exp $ */
/*
* Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <limits.h>
/*
* This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
* if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
*/
#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
void *
reallocarray(void *optr, size_t nmemb, size_t size)
{
if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
nmemb > 0 && SIZE_MAX / nmemb < size) {
errno = ENOMEM;
return NULL;
}
return realloc(optr, size * nmemb);
}
-31
View File
@@ -1,31 +0,0 @@
# Copyright 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.
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := image
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../libjpeg-turbo $(LOCAL_PATH)/../libpng $(LOCAL_PATH)/../giflib $(LOCAL_PATH)/../stream
LOCAL_SRC_FILES := \
image.c \
image_jpeg.c \
image_png.c \
image_gif.c \
image_utils.c \
java_wrapper.c
LOCAL_LDLIBS := -llog -ljnigraphics -lGLESv2
LOCAL_STATIC_LIBRARIES := jpeg-turbo png gif stream
include $(BUILD_SHARED_LIBRARY)
-28
View File
@@ -1,28 +0,0 @@
/*
* Copyright 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.
*/
//
// Created by Hippo on 12/27/2015.
//
#ifndef IMAGE_CONFIG_H
#define IMAGE_CONFIG_H
#define IMAGE_SUPPORT_JPEG
#define IMAGE_SUPPORT_PNG
#define IMAGE_SUPPORT_GIF
#endif //IMAGE_CONFIG_H
-337
View File
@@ -1,337 +0,0 @@
/*
* Copyright 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.
*/
//
// Created by Hippo on 12/27/2015.
//
#include "image.h"
#include "image_jpeg.h"
#include "image_png.h"
#include "image_gif.h"
#include "java_wrapper.h"
#include "../log.h"
static int get_format(JNIEnv* env, InputStream* stream)
{
unsigned char temp[2];
int read = read_input_stream(env, stream, temp, 0, 2);
if (read == 2) {
#ifdef IMAGE_SUPPORT_JPEG
if (temp[0] == IMAGE_JPEG_MAGIC_NUMBER_0 && temp[1] == IMAGE_JPEG_MAGIC_NUMBER_1) {
return IMAGE_FORMAT_JPEG;
}
#endif
#ifdef IMAGE_SUPPORT_PNG
if (temp[0] == IMAGE_PNG_MAGIC_NUMBER_0 && temp[1] == IMAGE_PNG_MAGIC_NUMBER_1) {
return IMAGE_FORMAT_PNG;
}
#endif
#ifdef IMAGE_SUPPORT_GIF
if (temp[0] == IMAGE_GIF_MAGIC_NUMBER_0 && temp[1] == IMAGE_GIF_MAGIC_NUMBER_1) {
return IMAGE_FORMAT_GIF;
}
#endif
}
return IMAGE_FORMAT_UNKNOWN;
}
void* decode(JNIEnv* env, InputStream* stream, bool partially, int* format)
{
unsigned char magic_numbers[2];
PatchHeadInputStream* patch_head_input_stream;
*format = get_format(env, stream);
switch (*format) {
#ifdef IMAGE_SUPPORT_JPEG
case IMAGE_FORMAT_JPEG:
magic_numbers[0] = IMAGE_JPEG_MAGIC_NUMBER_0;
magic_numbers[1] = IMAGE_JPEG_MAGIC_NUMBER_1;
break;
#endif
#ifdef IMAGE_SUPPORT_PNG
case IMAGE_FORMAT_PNG:
magic_numbers[0] = IMAGE_PNG_MAGIC_NUMBER_0;
magic_numbers[1] = IMAGE_PNG_MAGIC_NUMBER_1;
break;
#endif
#ifdef IMAGE_SUPPORT_GIF
case IMAGE_FORMAT_GIF:
magic_numbers[0] = IMAGE_GIF_MAGIC_NUMBER_0;
magic_numbers[1] = IMAGE_GIF_MAGIC_NUMBER_1;
break;
#endif
default:
LOGE(MSG("Can't detect format %d"), *format);
destroy_input_stream(get_env(), &stream);
return NULL;
}
patch_head_input_stream = create_patch_head_input_stream(stream, magic_numbers, 2);
if (patch_head_input_stream == NULL){
WTF_OM;
destroy_input_stream(get_env(), &stream);
return NULL;
}
switch (*format) {
#ifdef IMAGE_SUPPORT_JPEG
case IMAGE_FORMAT_JPEG:
return JPEG_decode(env, patch_head_input_stream, partially);
#endif
#ifdef IMAGE_SUPPORT_PNG
case IMAGE_FORMAT_PNG:
return PNG_decode(env, patch_head_input_stream, partially);
#endif
#ifdef IMAGE_SUPPORT_GIF
case IMAGE_FORMAT_GIF:
return GIF_decode(env, patch_head_input_stream, partially);
#endif
default:
LOGE(MSG("Can't detect format %d"), *format);
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
}
bool complete(void* image, int format)
{
switch (format) {
#ifdef IMAGE_SUPPORT_JPEG
case IMAGE_FORMAT_JPEG:
return JPEG_complete((JPEG*) image);
#endif
#ifdef IMAGE_SUPPORT_PNG
case IMAGE_FORMAT_PNG:
return PNG_complete((PNG*) image);
#endif
#ifdef IMAGE_SUPPORT_GIF
case IMAGE_FORMAT_GIF:
return GIF_complete((GIF*) image);
#endif
default:
LOGE(MSG("Can't detect format %d"), format);
return false;
}
}
bool is_completed(void* image, int format)
{
switch (format) {
#ifdef IMAGE_SUPPORT_JPEG
case IMAGE_FORMAT_JPEG:
return JPEG_is_completed((JPEG*) image);
#endif
#ifdef IMAGE_SUPPORT_PNG
case IMAGE_FORMAT_PNG:
return PNG_is_completed((PNG*) image);
#endif
#ifdef IMAGE_SUPPORT_GIF
case IMAGE_FORMAT_GIF:
return GIF_is_completed((GIF*) image);
#endif
default:
LOGE(MSG("Can't detect format %d"), format);
return false;
}
}
int get_width(void* image, int format)
{
switch (format) {
#ifdef IMAGE_SUPPORT_JPEG
case IMAGE_FORMAT_JPEG:
return JPEG_get_width((JPEG*) image);
#endif
#ifdef IMAGE_SUPPORT_PNG
case IMAGE_FORMAT_PNG:
return PNG_get_width((PNG*) image);
#endif
#ifdef IMAGE_SUPPORT_GIF
case IMAGE_FORMAT_GIF:
return GIF_get_width((GIF*) image);
#endif
default:
LOGE(MSG("Can't detect format %d"), format);
return -1;
}
}
int get_height(void* image, int format)
{
switch (format) {
#ifdef IMAGE_SUPPORT_JPEG
case IMAGE_FORMAT_JPEG:
return JPEG_get_height((JPEG*) image);
#endif
#ifdef IMAGE_SUPPORT_PNG
case IMAGE_FORMAT_PNG:
return PNG_get_height((PNG*) image);
#endif
#ifdef IMAGE_SUPPORT_GIF
case IMAGE_FORMAT_GIF:
return GIF_get_height((GIF*) image);
#endif
default:
LOGE(MSG("Can't detect format %d"), format);
return -1;
}
}
void render(void* image, int format, int src_x, int src_y,
void* dst, int dst_w, int dst_h, int dst_x, int dst_y,
int width, int height, bool fill_blank, int default_color)
{
switch (format) {
#ifdef IMAGE_SUPPORT_JPEG
case IMAGE_FORMAT_JPEG:
JPEG_render((JPEG*) image, src_x, src_y,
dst, dst_w, dst_h, dst_x, dst_y,
width, height, fill_blank, default_color);
break;
#endif
#ifdef IMAGE_SUPPORT_PNG
case IMAGE_FORMAT_PNG:
PNG_render((PNG*) image, src_x, src_y,
dst, dst_w, dst_h, dst_x, dst_y,
width, height, fill_blank, default_color);
break;
#endif
#ifdef IMAGE_SUPPORT_GIF
case IMAGE_FORMAT_GIF:
GIF_render((GIF*) image, src_x, src_y,
dst, dst_w, dst_h, dst_x, dst_y,
width, height, fill_blank, default_color);
break;
#endif
default:
LOGE(MSG("Can't detect format %d"), format);
break;
}
}
void advance(void* image, int format)
{
switch (format) {
#ifdef IMAGE_SUPPORT_JPEG
case IMAGE_FORMAT_JPEG:
JPEG_advance((JPEG*) image);
break;
#endif
#ifdef IMAGE_SUPPORT_PNG
case IMAGE_FORMAT_PNG:
PNG_advance((PNG*) image);
break;
#endif
#ifdef IMAGE_SUPPORT_GIF
case IMAGE_FORMAT_GIF:
GIF_advance((GIF*) image);
break;
#endif
default:
LOGE(MSG("Can't detect format %d"), format);
}
}
int get_delay(void* image, int format)
{
switch (format) {
#ifdef IMAGE_SUPPORT_JPEG
case IMAGE_FORMAT_JPEG:
return JPEG_get_delay((JPEG*) image);
#endif
#ifdef IMAGE_SUPPORT_PNG
case IMAGE_FORMAT_PNG:
return PNG_get_delay((PNG*) image);
#endif
#ifdef IMAGE_SUPPORT_GIF
case IMAGE_FORMAT_GIF:
return GIF_get_delay((GIF*) image);
#endif
default:
LOGE(MSG("Can't detect format %d"), format);
return false;
}
}
int get_frame_count(void* image, int format)
{
switch (format) {
#ifdef IMAGE_SUPPORT_JPEG
case IMAGE_FORMAT_JPEG:
return JPEG_get_frame_count((JPEG*) image);
#endif
#ifdef IMAGE_SUPPORT_PNG
case IMAGE_FORMAT_PNG:
return PNG_get_frame_count((PNG*) image);
#endif
#ifdef IMAGE_SUPPORT_GIF
case IMAGE_FORMAT_GIF:
return GIF_get_frame_count((GIF*) image);
#endif
default:
LOGE(MSG("Can't detect format %d"), format);
return false;
}
}
bool is_opaque(void* image, int format)
{
switch (format) {
#ifdef IMAGE_SUPPORT_JPEG
case IMAGE_FORMAT_JPEG:
return JPEG_is_opaque((JPEG*) image);
#endif
#ifdef IMAGE_SUPPORT_PNG
case IMAGE_FORMAT_PNG:
return PNG_is_opaque((PNG*) image);
#endif
#ifdef IMAGE_SUPPORT_GIF
case IMAGE_FORMAT_GIF:
return GIF_is_opaque((GIF*) image);
#endif
default:
LOGE(MSG("Can't detect format %d"), format);
return false;
}
}
void recycle(void* image, int format)
{
switch (format) {
#ifdef IMAGE_SUPPORT_JPEG
case IMAGE_FORMAT_JPEG:
JPEG_recycle((JPEG*) image);
break;
#endif
#ifdef IMAGE_SUPPORT_PNG
case IMAGE_FORMAT_PNG:
PNG_recycle((PNG*) image);
break;
#endif
#ifdef IMAGE_SUPPORT_GIF
case IMAGE_FORMAT_GIF:
GIF_recycle((GIF*) image);
break;
#endif
default:
LOGE(MSG("Can't detect format %d"), format);
}
}
-54
View File
@@ -1,54 +0,0 @@
/*
* Copyright 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.
*/
//
// Created by Hippo on 12/27/2015.
//
#ifndef IMAGE_IMAGE_H
#define IMAGE_IMAGE_H
#include <stdbool.h>
#include "config.h"
#include "input_stream.h"
#define IMAGE_FORMAT_UNKNOWN -1
#ifdef IMAGE_SUPPORT_JPEG
#define IMAGE_FORMAT_JPEG 0x00
#endif
#ifdef IMAGE_SUPPORT_PNG
#define IMAGE_FORMAT_PNG 0x01
#endif
#ifdef IMAGE_SUPPORT_GIF
#define IMAGE_FORMAT_GIF 0x02
#endif
void* decode(JNIEnv* env, InputStream* stream, bool partially, int* format);
bool complete(void* image, int format);
bool is_completed(void* image, int format);
int get_width(void* image, int format);
int get_height(void* image, int format);
void render(void* image, int format, int src_x, int src_y,
void* dst, int dst_w, int dst_h, int dst_x, int dst_y,
int width, int height, bool fill_blank, int default_color);
void advance(void* image, int format);
int get_delay(void* image, int format);
int get_frame_count(void* image, int format);
bool is_opaque(void* image, int format);
void recycle(void* image, int format);
#endif //IMAGE_IMAGE_H
-511
View File
@@ -1,511 +0,0 @@
/*
* Copyright 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.
*/
//
// Created by Hippo on 12/27/2015.
//
#include "config.h"
#ifdef IMAGE_SUPPORT_GIF
#include <stdlib.h>
#include "image_gif.h"
#include "image_utils.h"
#include "java_wrapper.h"
#include "../log.h"
#include "../utils.h"
static int error_code = 0;
typedef struct {
unsigned char red;
unsigned char green;
unsigned char blue;
unsigned char alpha;
} RGBA;
static int custom_read_fun(GifFileType* gif, GifByteType* bytes, int size) {
PatchHeadInputStream* patch_head_input_stream = gif->UserData;
JNIEnv *env = get_env();
if (env == NULL) {
LOGE(MSG("Can't get JNIEnv"));
return 0;
}
return read_patch_head_input_stream(env, patch_head_input_stream, bytes, 0, size);
}
static void generate_prepare(GIF_FRAME_INFO* frame_info_array, int count)
{
int disposal = 0xff;
int i;
for (i = 0; i < count; i++){
GIF_FRAME_INFO* frame_info = frame_info_array + i;
switch (disposal) {
case DISPOSAL_UNSPECIFIED:
case DISPOSE_DO_NOT:
frame_info->prepare = IMAGE_GIF_PREPARE_NONE;
break;
case DISPOSE_BACKGROUND:
frame_info->prepare = IMAGE_GIF_PREPARE_BACKGROUND;
break;
case DISPOSE_PREVIOUS:
frame_info->prepare = IMAGE_GIF_PREPARE_USE_BACKUP;
break;
default:
frame_info->prepare = IMAGE_GIF_PREPARE_BACKGROUND;
break;
}
disposal = frame_info->disposal;
}
}
static void read_gcb(GifFileType* gif_file, int index, GIF_FRAME_INFO* frame_info)
{
GraphicsControlBlock gcb;
if (DGifSavedExtensionToGCB(gif_file, index, &gcb) == GIF_OK) {
frame_info->tran = gcb.TransparentColor;
frame_info->delay = gcb.DelayTime * 10;
frame_info->disposal = gcb.DisposalMode;
frame_info->prepare = IMAGE_GIF_PREPARE_UNKNOWN;
} else {
frame_info->tran = -1;
frame_info->delay = 0;
frame_info->disposal = DISPOSE_DO_NOT;
frame_info->prepare = IMAGE_GIF_PREPARE_UNKNOWN;
}
}
static void fix_gif_file(GifFileType* gif_file) {
if (gif_file->ImageCount == 0) {
return;
}
SavedImage last_image = gif_file->SavedImages[gif_file->ImageCount - 1];
// If RasterBits is NULL, discard this frame
if (last_image.RasterBits == NULL) {
gif_file->ImageCount--;
// Free last image
if (last_image.ImageDesc.ColorMap != NULL) {
GifFreeMapObject(last_image.ImageDesc.ColorMap);
last_image.ImageDesc.ColorMap = NULL;
}
GifFreeExtensions(&last_image.ExtensionBlockCount, &last_image.ExtensionBlocks);
}
}
void* GIF_decode(JNIEnv* env, PatchHeadInputStream* patch_head_input_stream, bool partially)
{
GIF* gif = NULL;
GifFileType* gif_file = NULL;
void* buffer = NULL;
void*shown_buffer = NULL;
GIF_FRAME_INFO* frame_info_array = NULL;
int i;
gif = (GIF*) malloc(sizeof(GIF));
if (gif == NULL) {
WTF_OM;
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
// Open
gif_file = DGifOpen(patch_head_input_stream, &custom_read_fun, &error_code);
if (gif_file == NULL) {
WTF_OM;
free(gif);
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
// Buffer
buffer = malloc(gif_file->SWidth * gif_file->SHeight * sizeof(RGBA));
shown_buffer = malloc(gif_file->SWidth * gif_file->SHeight * sizeof(RGBA));
if (buffer == NULL || shown_buffer == NULL) {
WTF_OM;
free(buffer);
free(shown_buffer);
DGifCloseFile(gif_file, &error_code);
free(gif);
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
if (partially) {
// Glance
if (DGifGlance(gif_file) != GIF_OK) {
LOGE(MSG("GIF error code %d"), error_code);
DGifCloseFile(gif_file, &error_code);
free(buffer);
free(gif);
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
// Frame info
frame_info_array = (GIF_FRAME_INFO*) malloc(sizeof(GIF_FRAME_INFO));
if (frame_info_array == NULL) {
WTF_OM;
DGifCloseFile(gif_file, &error_code);
free(buffer);
free(gif);
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
// Read gcb
read_gcb(gif_file, 0, frame_info_array);
gif->partially = true;
gif->patch_head_input_stream = patch_head_input_stream;
} else {
// Slurp
if (DGifSlurp(gif_file) == GIF_ERROR) {
fix_gif_file(gif_file);
}
if (gif_file->ImageCount <= 0) {
LOGE(MSG("No frame"));
DGifCloseFile(gif_file, &error_code);
free(buffer);
free(gif);
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
// Frame info
frame_info_array = (GIF_FRAME_INFO*) malloc(gif_file->ImageCount * sizeof(GIF_FRAME_INFO));
if (frame_info_array == NULL) {
WTF_OM;
DGifCloseFile(gif_file, &error_code);
free(buffer);
free(gif);
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
// Read gcb
for (i = 0; i < gif_file->ImageCount; i++) {
read_gcb(gif_file, i, frame_info_array + i);
}
// Generate prepare
generate_prepare(frame_info_array, gif_file->ImageCount);
// Close input stream
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
gif->partially = false;
gif->patch_head_input_stream = NULL;
}
gif->gif_file = gif_file;
gif->frame_info_array = frame_info_array;
gif->buffer = buffer;
gif->buffer_index = -1;
gif->backup = NULL;
gif->shown_buffer = shown_buffer;
GIF_advance(gif);
return gif;
}
bool GIF_complete(GIF* gif)
{
int i;
if (!gif->partially) {
return true;
}
if (gif->gif_file == NULL || gif->patch_head_input_stream == NULL) {
LOGE(MSG("Some stuff is NULL"));
return false;
}
if (DGifSlurp(gif->gif_file) == GIF_ERROR) {
fix_gif_file(gif->gif_file);
}
// Close input stream
close_patch_head_input_stream(get_env(), gif->patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &gif->patch_head_input_stream);
gif->patch_head_input_stream = NULL;
gif->partially = false;
gif->frame_info_array = (GIF_FRAME_INFO*) realloc(gif->frame_info_array,
gif->gif_file->ImageCount * sizeof(GIF_FRAME_INFO));
if (gif->frame_info_array == NULL) {
WTF_OM;
return false;
}
// Read gcb
for (i = 0; i < gif->gif_file->ImageCount; i++) {
read_gcb(gif->gif_file, i, gif->frame_info_array + i);
}
// Generate prepare
generate_prepare(gif->frame_info_array, gif->gif_file->ImageCount);
return true;
}
bool GIF_is_completed(GIF* gif)
{
return !gif->partially;
}
int GIF_get_width(GIF* gif)
{
return gif->gif_file->SWidth;
}
int GIF_get_height(GIF* gif)
{
return gif->gif_file->SHeight;
}
void GIF_render(GIF* gif, int src_x, int src_y,
void* dst, int dst_w, int dst_h, int dst_x, int dst_y,
int width, int height, bool fill_blank, int default_color)
{
copy_pixels(gif->shown_buffer, gif->gif_file->SWidth, gif->gif_file->SHeight, src_x, src_y,
dst, dst_w, dst_h, dst_x, dst_y,
width, height, fill_blank, default_color);
}
static void backup(GIF* gif)
{
if (gif->backup == NULL) {
gif->backup = (unsigned char*) malloc((size_t) (gif->gif_file->SWidth * gif->gif_file->SHeight * 4));
if (gif->backup == NULL) {
WTF_OM;
return;
}
}
memcpy(gif->backup, gif->buffer, (size_t) (gif->gif_file->SWidth * gif->gif_file->SHeight * 4));
}
static void restore(GIF* gif)
{
if (gif->backup == NULL) {
LOGE(MSG("Backup is NULL"));
} else {
memcpy(gif->buffer, gif->backup, (size_t) (gif->gif_file->SWidth * gif->gif_file->SHeight * 4));
}
}
static void switch_buffer_backup(GIF* gif)
{
unsigned char* temp;
if (gif->backup == NULL) {
backup(gif);
} else {
temp = gif->buffer;
gif->buffer = gif->backup;
gif->backup = temp;
}
}
static void clear(RGBA* pixels, int num, RGBA color) {
RGBA* ptr = pixels;
int i;
for (i = 0; i < num; i++) {
*(ptr++) = color;
}
}
static bool get_color_from_table(const ColorMapObject* cmap, int index,
RGBA* color) {
if (cmap == NULL || index < 0 || index >= cmap->ColorCount) {
return false;
} else {
GifColorType gct = cmap->Colors[index];
color->red = gct.Red;
color->green = gct.Green;
color->blue = gct.Blue;
color->alpha = 0xff;
return true;
}
}
static void clear_bg(GifFileType* gif_file, void* pixels)
{
RGBA color;
if (!get_color_from_table(gif_file->SColorMap, gif_file->SBackGroundColor, &color)) {
color.red = 0x00;
color.green = 0x00;
color.blue = 0x00;
color.alpha = 0x00;
}
clear(pixels, gif_file->SWidth * gif_file->SHeight, color);
}
static void copy_line(GifByteType* src, RGBA* dst,
const ColorMapObject* cmap, int tran, int len)
{
for (; len > 0; len--, src++, dst++) {
int index = *src;
if (tran == -1 || index != tran) {
get_color_from_table(cmap, index, dst);
}
}
}
static void blend(GifFileType* gif_file, int index, void* pixels, int tran)
{
int width = gif_file->SWidth;
int height = gif_file->SHeight;
SavedImage cur = gif_file->SavedImages[index];
GifImageDesc desc = cur.ImageDesc;
int copy_width = MIN(width - desc.Left, desc.Width);
int copy_height = MIN(height - desc.Top, desc.Height);
ColorMapObject *cmap = desc.ColorMap;
GifByteType* src = cur.RasterBits;
RGBA* dst = pixels;
GifByteType* src_ptr;
RGBA* dst_ptr;
size_t len;
int i;
if (cmap == NULL) {
cmap = gif_file->SColorMap;
}
if (cmap != NULL) {
for (i = 0; i < copy_height; i++) {
src_ptr = src + (i * desc.Width);
dst_ptr = dst + ((desc.Top + i) * width + desc.Left);
len = (size_t) copy_width;
copy_line(src_ptr, dst_ptr, cmap, tran, len);
}
} else {
LOGW(MSG("Can't find color map"));
}
}
void GIF_advance(GIF* gif)
{
int index;
GIF_FRAME_INFO frame_info;
index = (gif->buffer_index + 1) % gif->gif_file->ImageCount;
if (index != 0 && gif->partially) {
LOGE(MSG("The png is only decoded partially. Only the first frame can be shown."));
return;
}
if (gif->frame_info_array == NULL) {
frame_info.tran = -1;
frame_info.disposal = DISPOSE_DO_NOT;
frame_info.delay = 0;
frame_info.prepare = IMAGE_GIF_PREPARE_BACKGROUND;
} else {
memcpy(&frame_info, gif->frame_info_array + index, sizeof(GIF_FRAME_INFO));
}
if (frame_info.disposal == DISPOSE_PREVIOUS && frame_info.prepare == IMAGE_GIF_PREPARE_USE_BACKUP) {
switch_buffer_backup(gif);
} else {
// Backup
if (frame_info.disposal == DISPOSE_PREVIOUS) {
backup(gif);
}
// Prepare
switch (frame_info.prepare) {
case IMAGE_GIF_PREPARE_NONE:
// Do nothing
break;
default:
case IMAGE_GIF_PREPARE_BACKGROUND:
// Set bg
clear_bg(gif->gif_file, gif->buffer);
break;
case IMAGE_GIF_PREPARE_USE_BACKUP:
restore(gif);
break;
}
}
blend(gif->gif_file, index, gif->buffer, frame_info.tran);
// Copy to shown buffer
memcpy(gif->shown_buffer, gif->buffer, (size_t) (gif->gif_file->SWidth * gif->gif_file->SHeight * 4));
gif->buffer_index = index;
}
int GIF_get_delay(GIF* gif)
{
if (gif->frame_info_array == NULL) {
return 0;
} else {
return gif->frame_info_array[gif->buffer_index].delay;
}
}
int GIF_get_frame_count(GIF* gif)
{
return gif->gif_file->ImageCount;
}
bool GIF_is_opaque(GIF* gif)
{
return gif->frame_info_array->tran < 0;
}
void GIF_recycle(GIF* gif)
{
DGifCloseFile(gif->gif_file, &error_code);
gif->gif_file = NULL;
free(gif->frame_info_array);
gif->frame_info_array = NULL;
free(gif->buffer);
gif->buffer = NULL;
free(gif->backup);
gif->backup = NULL;
free(gif->shown_buffer);
gif->shown_buffer = NULL;
if (gif->patch_head_input_stream != NULL) {
close_patch_head_input_stream(get_env(), gif->patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &gif->patch_head_input_stream);
gif->patch_head_input_stream = NULL;
}
}
#endif // IMAGE_SUPPORT_GIF
-77
View File
@@ -1,77 +0,0 @@
/*
* Copyright 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.
*/
//
// Created by Hippo on 12/27/2015.
//
#ifndef IMAGE_IMAGE_GIF_H
#define IMAGE_IMAGE_GIF_H
#include "config.h"
#ifdef IMAGE_SUPPORT_GIF
#include <stdbool.h>
#include "patch_head_input_stream.h"
#include "gif_lib.h"
#define IMAGE_GIF_MAGIC_NUMBER_0 0x47
#define IMAGE_GIF_MAGIC_NUMBER_1 0x49
#define IMAGE_GIF_PREPARE_UNKNOWN 0x00
#define IMAGE_GIF_PREPARE_NONE 0x01
#define IMAGE_GIF_PREPARE_BACKGROUND 0x02
#define IMAGE_GIF_PREPARE_USE_BACKUP 0x03
typedef struct
{
int tran;
int disposal;
int delay;
int prepare;
} GIF_FRAME_INFO;
typedef struct
{
GifFileType* gif_file;
GIF_FRAME_INFO* frame_info_array;
void* buffer;
int buffer_index;
void* backup;
bool partially;
// Use extra buffer to avoid blink
void* shown_buffer;
PatchHeadInputStream* patch_head_input_stream;
} GIF;
void* GIF_decode(JNIEnv* env, PatchHeadInputStream* patch_head_input_stream, bool partially);
bool GIF_complete(GIF* gif);
bool GIF_is_completed(GIF* gif);
int GIF_get_width(GIF* gif);
int GIF_get_height(GIF* gif);
void GIF_render(GIF* gif, int src_x, int src_y,
void* dst, int dst_w, int dst_h, int dst_x, int dst_y,
int width, int height, bool fill_blank, int default_color);
void GIF_advance(GIF* gif);
int GIF_get_delay(GIF* gif);
int GIF_get_frame_count(GIF* gif);
bool GIF_is_opaque(GIF* gif);
void GIF_recycle(GIF* gif);
#endif // IMAGE_SUPPORT_GIF
#endif // IMAGE_IMAGE_GIF_H
-192
View File
@@ -1,192 +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.
*/
//
// Created by Hippo on 1/3/2016.
//
#include "config.h"
#ifdef IMAGE_SUPPORT_JPEG
#include <setjmp.h>
#include <stdlib.h>
#include <stdio.h>
#include "jpeglib.h"
#include "image_jpeg.h"
#include "image_utils.h"
#include "java_wrapper.h"
#include "../log.h"
struct my_error_mgr {
struct jpeg_error_mgr pub;
jmp_buf setjmp_buffer;
};
typedef struct my_error_mgr * my_error_ptr;
static char emsg[JMSG_LENGTH_MAX];
static void my_error_exit(j_common_ptr cinfo) {
my_error_ptr myerr = (my_error_ptr) cinfo->err;
(*cinfo->err->format_message)(cinfo, emsg);
longjmp(myerr->setjmp_buffer, 1);
}
static size_t custom_read(void * custom_stuff, unsigned char * buffer, size_t size) {
PatchHeadInputStream* patch_head_input_stream = custom_stuff;
JNIEnv *env = get_env();
if (env == NULL) {
LOGE(MSG("Can't get JNIEnv"));
return 0;
}
return read_patch_head_input_stream(env, patch_head_input_stream, buffer, 0, size);
}
void* JPEG_decode(JNIEnv* env, PatchHeadInputStream* patch_head_input_stream, bool partially)
{
JPEG* jpeg = NULL;
struct jpeg_decompress_struct cinfo;
struct my_error_mgr jerr;
unsigned char* buffer = NULL;
size_t stride;
unsigned char* line_buffer_array[3];
int read_lines;
jpeg = (JPEG*) malloc(sizeof(JPEG));
if (jpeg == NULL) {
WTF_OM;
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
// Init
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
if (setjmp(jerr.setjmp_buffer)) {
LOGE(MSG("%s"), emsg);
free(jpeg);
free(buffer);
jpeg_destroy_decompress(&cinfo);
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
jpeg_create_decompress(&cinfo);
jpeg_custom_src(&cinfo, &custom_read, patch_head_input_stream);
jpeg_read_header(&cinfo, TRUE);
// Start decompress
cinfo.out_color_space = JCS_EXT_RGBA;
jpeg_start_decompress(&cinfo);
stride = cinfo.output_components * cinfo.output_width;
buffer = malloc(stride * cinfo.output_height);
if (buffer == NULL) {
free(jpeg);
jpeg_destroy_decompress(&cinfo);
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
// Copy buffer
line_buffer_array[0] = buffer;
line_buffer_array[1] = line_buffer_array[0] + stride;
line_buffer_array[2] = line_buffer_array[1] + stride;
while (cinfo.output_scanline < cinfo.output_height) {
read_lines = jpeg_read_scanlines(&cinfo, line_buffer_array, 3);
line_buffer_array[0] += stride * read_lines;
line_buffer_array[1] = line_buffer_array[0] + stride;
line_buffer_array[2] = line_buffer_array[1] + stride;
}
// Finish decompress
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
// Close stream
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
// Fill jpeg
jpeg->width = cinfo.output_width;
jpeg->height = cinfo.output_height;
jpeg->buffer = buffer;
return jpeg;
}
bool JPEG_complete(JPEG* jpeg)
{
return true;
}
bool JPEG_is_completed(JPEG* jpeg)
{
return true;
}
int JPEG_get_width(JPEG* jpeg)
{
return jpeg->width;
}
int JPEG_get_height(JPEG* jpeg)
{
return jpeg->height;
}
void JPEG_render(JPEG* jpeg, int src_x, int src_y,
void* dst, int dst_w, int dst_h, int dst_x, int dst_y,
int width, int height, bool fill_blank, int default_color)
{
copy_pixels(jpeg->buffer, jpeg->width, jpeg->height, src_x, src_y,
dst, dst_w, dst_h, dst_x, dst_y,
width, height, fill_blank, default_color);
}
void JPEG_advance(JPEG* jpeg)
{
}
int JPEG_get_delay(JPEG* jpeg)
{
return 0;
}
int JPEG_get_frame_count(JPEG* jpeg)
{
return 1;
}
bool JPEG_is_opaque(JPEG* jpeg)
{
return true;
}
void JPEG_recycle(JPEG* jpeg)
{
free(jpeg->buffer);
jpeg->buffer = NULL;
free(jpeg);
}
#endif // IMAGE_SUPPORT_JPEG
-57
View File
@@ -1,57 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// Created by Hippo on 1/3/2016.
//
#ifndef IMAGE_IMAGE_JPEG_H
#define IMAGE_IMAGE_JPEG_H
#include "config.h"
#ifdef IMAGE_SUPPORT_JPEG
#include <stdbool.h>
#include "patch_head_input_stream.h"
#define IMAGE_JPEG_MAGIC_NUMBER_0 0xFF
#define IMAGE_JPEG_MAGIC_NUMBER_1 0xD8
typedef struct
{
unsigned int width;
unsigned int height;
unsigned char* buffer;
} JPEG;
void* JPEG_decode(JNIEnv* env, PatchHeadInputStream* patch_head_input_stream, bool partially);
bool JPEG_complete(JPEG* jpeg);
bool JPEG_is_completed(JPEG* jpeg);
int JPEG_get_width(JPEG* jpeg);
int JPEG_get_height(JPEG* jpeg);
void JPEG_render(JPEG* jpeg, int src_x, int src_y,
void* dst, int dst_w, int dst_h, int dst_x, int dst_y,
int width, int height, bool fill_blank, int default_color);
void JPEG_advance(JPEG* jpeg);
int JPEG_get_delay(JPEG* jpeg);
int JPEG_get_frame_count(JPEG* jpeg);
bool JPEG_is_opaque(JPEG* jpeg);
void JPEG_recycle(JPEG* jpeg);
#endif // IMAGE_SUPPORT_JPEG
#endif // IMAGE_IMAGE_JPEG_H
-601
View File
@@ -1,601 +0,0 @@
/*
* Copyright 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.
*/
//
// Created by Hippo on 12/27/2015.
//
#include "config.h"
#ifdef IMAGE_SUPPORT_PNG
#include <stdlib.h>
#include "../log.h"
#include "../utils.h"
#include "image_png.h"
#include "image_utils.h"
#include "java_wrapper.h"
static void user_read_fn(png_structp png_ptr,
png_bytep data, png_size_t length)
{
PatchHeadInputStream* patch_head_input_stream = png_get_io_ptr(png_ptr);
JNIEnv *env = get_env();
if (env == NULL) {
LOGE(MSG("Can't get JNIEnv"));
}
read_patch_head_input_stream(env, patch_head_input_stream, data, 0, length);
}
static void user_error_fn(png_structp png_ptr,
png_const_charp error_msg)
{
LOGE(MSG("%s"), error_msg);
}
static void user_warn_fn(png_structp png_ptr,
png_const_charp error_msg)
{
LOGW(MSG("%s"), error_msg);
}
static void free_frame_info_array(PNG_FRAME_INFO* frame_info_array, unsigned int count)
{
int i;
if (frame_info_array == NULL) {
return;
}
for (i = 0; i < count; i++) {
PNG_FRAME_INFO* frame_info = frame_info_array + i;
free(frame_info->buffer);
frame_info->buffer = NULL;
}
free(frame_info_array);
}
static bool read_image(png_structp png_ptr, unsigned char* buffer, unsigned int width, unsigned int height)
{
int i;
unsigned char** line_buffer_ptr_array = (unsigned char**) malloc(height * sizeof(unsigned char*));
if (line_buffer_ptr_array == NULL) {
WTF_OM;
return false;
}
for (i = 0; i < height; i++) {
line_buffer_ptr_array[i] = buffer + (width * i * 4);
}
png_read_image(png_ptr, line_buffer_ptr_array);
free(line_buffer_ptr_array);
return true;
}
static void read_frame(png_structp png_ptr, png_infop info_ptr, PNG_FRAME_INFO* frame_info)
{
unsigned int width;
unsigned int height;
unsigned int offset_x;
unsigned int offset_y;
unsigned short delay_num;
unsigned short delay_den;
unsigned char dop;
unsigned char bop;
unsigned int delay;
unsigned char* buffer = NULL;
png_read_frame_head(png_ptr, info_ptr);
png_get_next_frame_fcTL(png_ptr, info_ptr, &width, &height, &offset_x, &offset_y, &delay_num, &delay_den, &dop, &bop);
delay = 1000u * delay_num / delay_den;
frame_info->width = width;
frame_info->height = height;
frame_info->offset_x = offset_x;
frame_info->offset_y = offset_y;
frame_info->delay = delay;
frame_info->dop = dop;
frame_info->bop = bop;
frame_info->pop = IMAGE_PNG_PREPARE_UNKNOWN;
buffer = (unsigned char*) malloc(width * height * 4);
if (buffer == NULL) {
frame_info->buffer = NULL;
return;
}
read_image(png_ptr, buffer, width, height);
frame_info->buffer = buffer;
}
static void generate_pop(PNG_FRAME_INFO* frame_info_array, int count)
{
unsigned char dop = 0xff;
int i;
for (i = 0; i < count; i++){
PNG_FRAME_INFO* frame_info = frame_info_array + i;
switch (dop) {
case PNG_DISPOSE_OP_NONE:
frame_info->pop = IMAGE_PNG_PREPARE_NONE;
break;
case PNG_DISPOSE_OP_BACKGROUND:
frame_info->pop = IMAGE_PNG_PREPARE_BACKGROUND;
break;
case PNG_DISPOSE_OP_PREVIOUS:
frame_info->pop = IMAGE_PNG_PREPARE_USE_BACKUP;
break;
default:
frame_info->pop = IMAGE_PNG_PREPARE_BACKGROUND;
break;
}
dop = frame_info->dop;
}
}
void* PNG_decode(JNIEnv* env, PatchHeadInputStream* patch_head_input_stream, bool partially)
{
PNG *png = NULL;
png_structp png_ptr = NULL;
png_infop info_ptr = NULL;
bool apng;
unsigned int width;
unsigned int height;
int color_type;
int bit_depth;
bool is_opaque;
unsigned char* buffer = NULL;
unsigned int frame_count = 0;
bool hide_first_frame = false;
PNG_FRAME_INFO* frame_info_array = NULL;
int i;
png = (PNG *) malloc(sizeof(PNG));
if (png == NULL) {
WTF_OM;
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, &user_error_fn, &user_warn_fn);
if (png_ptr == NULL) {
free(png);
png = NULL;
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
free(png);
png = NULL;
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
if (setjmp(png_jmpbuf(png_ptr))) {
LOGE(MSG("Error in png decode"));
free_frame_info_array(frame_info_array, frame_count);
frame_info_array = NULL;
free(buffer);
buffer = NULL;
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
free(png);
png = NULL;
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
// Set custom read function
png_set_read_fn(png_ptr, patch_head_input_stream, &user_read_fn);
// Get png info
png_read_info(png_ptr, info_ptr);
// Check apng
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_acTL)) {
apng = true;
} else {
apng = false;
}
// PNG info
width = png_get_image_width(png_ptr, info_ptr);
height = png_get_image_height(png_ptr, info_ptr);
color_type = png_get_color_type(png_ptr, info_ptr);
bit_depth = png_get_bit_depth(png_ptr, info_ptr);
// Create buffer
buffer = (unsigned char*) malloc(width * height * 4);
if (buffer == NULL) {
WTF_OM;
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
free(png);
png = NULL;
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
if (apng) {
// Get frame count
frame_count = png_get_num_frames(png_ptr, info_ptr);
hide_first_frame = png_get_first_frame_is_hidden(png_ptr, info_ptr);
if (hide_first_frame) {
frame_count--;
}
// Create frame info array
frame_info_array = (PNG_FRAME_INFO*) calloc(frame_count, sizeof(PNG_FRAME_INFO));
if (frame_info_array == NULL) {
WTF_OM;
free(buffer);
buffer = NULL;
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
free(png);
png = NULL;
close_patch_head_input_stream(get_env(), patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &patch_head_input_stream);
return NULL;
}
}
// Configure to ARGB
png_set_expand(png_ptr);
if (bit_depth == 16) {
png_set_scale_16(png_ptr);
}
if (color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
png_set_gray_to_rgb(png_ptr);
}
if (!(color_type & PNG_COLOR_MASK_ALPHA)) {
is_opaque = true;
png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER);
} else {
is_opaque = false;
}
if (apng) {
if (hide_first_frame) {
// Skip first frame
read_image(png_ptr, buffer, width, height);
}
// Read first frame
read_frame(png_ptr, info_ptr, frame_info_array);
// Fix dop
if (frame_info_array->dop == PNG_DISPOSE_OP_PREVIOUS) {
frame_info_array->dop = PNG_DISPOSE_OP_BACKGROUND;
}
if (!partially || frame_count == 1) {
// Read all frame
for (i = 1; i < frame_count; read_frame(png_ptr, info_ptr, frame_info_array + i++));
// Generate pop
generate_pop(frame_info_array, frame_count);
// End read
png_read_end(png_ptr, info_ptr);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
// Close input stream
close_patch_head_input_stream(env, patch_head_input_stream);
destroy_patch_head_input_stream(env, &patch_head_input_stream);
png->partially = false;
png->png_ptr = NULL;
png->info_ptr = NULL;
png->patch_head_input_stream = NULL;
} else {
png->partially = true;
png->png_ptr = png_ptr;
png->info_ptr = info_ptr;
png->patch_head_input_stream = patch_head_input_stream;
}
// Fill PNG
png->width = width;
png->height = height;
png->is_opaque = is_opaque;
png->buffer = buffer;
png->apng = true;
png->buffer_index = -1;
png->frame_info_array = frame_info_array;
png->frame_count = frame_count;
png->backup = NULL;
// Render first frame
PNG_advance(png);
} else {
read_image(png_ptr, buffer, width, height);
// End read
png_read_end(png_ptr, info_ptr);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
// Close input stream
close_patch_head_input_stream(env, patch_head_input_stream);
destroy_patch_head_input_stream(env, &patch_head_input_stream);
// Fill PNG
png->width = width;
png->height = height;
png->buffer = buffer;
png->apng = false;
png->buffer_index = 0;
png->frame_info_array = NULL;
png->frame_count = 0;
png->backup = NULL;
png->partially = false;
png->png_ptr = NULL;
png->info_ptr = NULL;
png->patch_head_input_stream = NULL;
}
return png;
}
bool PNG_complete(PNG* png)
{
int i;
if (!png->partially) {
return true;
}
if (png->png_ptr == NULL || png->info_ptr == NULL || png->patch_head_input_stream == NULL) {
LOGE(MSG("Some stuff is NULL"));
return false;
}
// Read left frames
for (i = 1; i < png->frame_count; read_frame(png->png_ptr, png->info_ptr, png->frame_info_array + i++));
// Generate pop
generate_pop(png->frame_info_array, png->frame_count);
// End read
png_read_end(png->png_ptr, png->info_ptr);
png_destroy_read_struct(&png->png_ptr, &png->info_ptr, NULL);
// Close input stream
close_patch_head_input_stream(get_env(), png->patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &png->patch_head_input_stream);
// Clean up
png->partially = false;
png->png_ptr = NULL;
png->info_ptr = NULL;
png->patch_head_input_stream = NULL;
return true;
}
bool PNG_is_completed(PNG* png)
{
return !png->partially;
}
int PNG_get_width(PNG* png)
{
return png->width;
}
int PNG_get_height(PNG* png)
{
return png->height;
}
void PNG_render(PNG* png, int src_x, int src_y,
void* dst, int dst_w, int dst_h, int dst_x, int dst_y,
int width, int height, bool fill_blank, int default_color)
{
copy_pixels(png->buffer, png->width, png->height, src_x, src_y,
dst, dst_w, dst_h, dst_x, dst_y,
width, height, fill_blank, default_color);
}
static void backup(PNG* png)
{
if (png->backup == NULL) {
png->backup = (unsigned char*) malloc(png->width * png->height * 4);
if (png->backup == NULL) {
WTF_OM;
return;
}
}
memcpy(png->backup, png->buffer, png->width * png->height * 4);
}
static void restore(PNG* png)
{
if (png->backup == NULL) {
LOGE(MSG("Backup is NULL"));
} else {
memcpy(png->buffer, png->backup, png->width * png->height * 4);
}
}
static void switch_buffer_backup(PNG* png)
{
unsigned char* temp;
if (png->backup == NULL) {
backup(png);
} else {
temp = png->buffer;
png->buffer = png->backup;
png->backup = temp;
}
}
static void blend_over(unsigned char* dp, const unsigned char* sp, size_t len)
{
unsigned int i;
int u, v, al;
for (i = 0; i < len; i += 4, sp += 4, dp += 4) {
if (sp[3] == 255) {
memcpy(dp, sp, 4);
} else if (sp[3] != 0) {
if (dp[3] != 0) {
u = sp[3] * 255;
v = (255 - sp[3]) * dp[3];
al = u + v;
dp[0] = (unsigned char) ((sp[0] * u + dp[0] * v) / al);
dp[1] = (unsigned char) ((sp[1] * u + dp[1] * v) / al);
dp[2] = (unsigned char) ((sp[2] * u + dp[2] * v) / al);
dp[3] = (unsigned char) (al / 255);
} else {
memcpy(dp, sp, 4);
}
}
}
}
static void blend(unsigned char* src, int src_width, int src_height, int offset_x, int offset_y,
unsigned char* dst, int dst_width, int dst_height, bool blend_op_over)
{
int i;
unsigned char* src_ptr;
unsigned char* dst_ptr;
size_t len;
int copy_width = MIN(dst_width - offset_x, src_width);
int copy_height = MIN(dst_height - offset_y, src_height);
for (i = 0; i < copy_height; i++) {
src_ptr = src + (i * src_width * 4);
dst_ptr = dst + (((offset_y + i) * dst_width + offset_x) * 4);
len = (size_t) (copy_width * 4);
if (blend_op_over) {
blend_over(dst_ptr, src_ptr, len);
} else {
memcpy(dst_ptr, src_ptr, len);
}
}
}
void PNG_advance(PNG* png)
{
int index;
if (!png->apng) {
LOGW(MSG("It is not apng, no need to advance"));
return;
}
index = (png->buffer_index + 1) % png->frame_count;
if (index != 0 && png->partially) {
LOGE(MSG("The png is only decoded partially. Only the first frame can be shown."));
return;
}
PNG_FRAME_INFO* frame_info = png->frame_info_array + index;
if (frame_info->dop == PNG_DISPOSE_OP_PREVIOUS && frame_info->pop == IMAGE_PNG_PREPARE_USE_BACKUP) {
switch_buffer_backup(png);
} else {
// Backup
if (frame_info->dop == PNG_DISPOSE_OP_PREVIOUS) {
backup(png);
}
// Prepare
switch (frame_info->pop) {
case IMAGE_PNG_PREPARE_NONE:
// Do nothing
break;
default:
case IMAGE_PNG_PREPARE_BACKGROUND:
// Set transparent
memset(png->buffer, '\0', png->width * png->height * 4);
break;
case IMAGE_PNG_PREPARE_USE_BACKUP:
restore(png);
break;
}
}
blend(frame_info->buffer, frame_info->width, frame_info->height, frame_info->offset_x, frame_info->offset_y,
png->buffer, png->width, png->height, frame_info->bop == PNG_BLEND_OP_OVER);
png->buffer_index = index;
}
int PNG_get_delay(PNG* png)
{
if (png->apng) {
return png->frame_info_array[png->buffer_index].delay;
} else {
return 0;
}
}
int PNG_get_frame_count(PNG* png)
{
if (png->apng) {
return png->frame_count;
} else {
return 1;
}
}
bool PNG_is_opaque(PNG* png)
{
return png->is_opaque;
}
void PNG_recycle(PNG* png)
{
if (png == NULL) {
return;
}
free(png->buffer);
png->buffer = NULL;
free_frame_info_array(png->frame_info_array, png->frame_count);
png->frame_info_array = NULL;
free(png->backup);
png->backup = NULL;
if (png->png_ptr != NULL && png->info_ptr != NULL) {
png_destroy_read_struct(&png->png_ptr, &png->info_ptr, NULL);
}
png->png_ptr = NULL;
png->info_ptr = NULL;
if (png->patch_head_input_stream != NULL) {
close_patch_head_input_stream(get_env(), png->patch_head_input_stream);
destroy_patch_head_input_stream(get_env(), &png->patch_head_input_stream);
png->patch_head_input_stream = NULL;
}
}
#endif // IMAGE_SUPPORT_PNG
-85
View File
@@ -1,85 +0,0 @@
/*
* Copyright 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.
*/
//
// Created by Hippo on 12/27/2015.
//
#ifndef IMAGE_IMAGE_PNG_H
#define IMAGE_IMAGE_PNG_H
#include "config.h"
#ifdef IMAGE_SUPPORT_PNG
#include <stdbool.h>
#include "png.h"
#include "patch_head_input_stream.h"
#define IMAGE_PNG_MAGIC_NUMBER_0 0x89
#define IMAGE_PNG_MAGIC_NUMBER_1 0x50
#define IMAGE_PNG_PREPARE_UNKNOWN 0x00
#define IMAGE_PNG_PREPARE_NONE 0x01
#define IMAGE_PNG_PREPARE_BACKGROUND 0x02
#define IMAGE_PNG_PREPARE_USE_BACKUP 0x03
typedef struct {
unsigned char* buffer;
unsigned int width;
unsigned int height;
unsigned int offset_x;
unsigned int offset_y;
unsigned int delay; // ms
unsigned char dop;
unsigned char bop;
unsigned char pop;
} PNG_FRAME_INFO;
typedef struct
{
unsigned int width;
unsigned int height;
bool is_opaque;
unsigned char* buffer;
bool apng;
int buffer_index;
PNG_FRAME_INFO* frame_info_array;
unsigned int frame_count;
unsigned char* backup;
bool partially;
png_structp png_ptr;
png_infop info_ptr;
PatchHeadInputStream* patch_head_input_stream;
} PNG;
void* PNG_decode(JNIEnv* env, PatchHeadInputStream* patch_head_input_stream, bool partially);
bool PNG_complete(PNG* png);
bool PNG_is_completed(PNG* png);
int PNG_get_width(PNG* png);
int PNG_get_height(PNG* png);
void PNG_render(PNG* png, int src_x, int src_y,
void* dst, int dst_w, int dst_h, int dst_x, int dst_y,
int width, int height, bool fill_blank, int default_color);
void PNG_advance(PNG* png);
int PNG_get_delay(PNG* png);
int PNG_get_frame_count(PNG* png);
bool PNG_is_opaque(PNG* png);
void PNG_recycle(PNG* png);
#endif // IMAGE_SUPPORT_PNG
#endif // IMAGE_IMAGE_PNG_H
-184
View File
@@ -1,184 +0,0 @@
/*
* Copyright 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.
*/
//
// Created by Hippo on 12/27/2015.
//
#include "image_utils.h"
#include <stdlib.h>
#define LITTLE_ENDIAN 0x00
#define BIG_ENDIAN 0x01
static unsigned int endian = ~0U;
static unsigned int get_endian() {
unsigned int x = 1;
if (endian == ~0U) {
if (1 == ((char *)&x)[0]) {
endian = LITTLE_ENDIAN;
} else {
endian = BIG_ENDIAN;
}
}
return endian;
}
static int convert_color(int origin) {
int result;
unsigned char* orPtr = (unsigned char *) &origin;
unsigned char* rePtr = (unsigned char *) &result;
if (get_endian() == BIG_ENDIAN) {
rePtr[0] = orPtr[1];
rePtr[1] = orPtr[2];
rePtr[2] = orPtr[3];
rePtr[3] = orPtr[0];
} else {
rePtr[0] = orPtr[2];
rePtr[1] = orPtr[1];
rePtr[2] = orPtr[0];
rePtr[3] = orPtr[3];
}
return result;
}
static void memset_int(int* dst, int val, size_t size) {
int* maxPtr = dst + size;
int* ptr = dst;
while(ptr < maxPtr)
*ptr++ = val;
}
bool copy_pixels_internal(const void* src, int src_w, int src_h, int src_x, int src_y,
void* dst, int dst_w, int dst_h, int dst_x, int dst_y,
int width, int height, bool fill_blank, int color)
{
int left;
int line;
size_t line_stride;
int src_stride;
int src_pos;
int dst_pos;
size_t dst_blank_length;
// Sanitize
if (src_x < 0) {
width -= src_x;
dst_x -= src_x;
src_x = 0;
}
if (dst_x < 0) {
width -= dst_x;
src_x -= dst_x;
dst_x = 0;
}
if (width <= 0) {
return false;
}
if (src_y < 0) {
height -= src_y;
dst_y -= src_y;
src_y = 0;
}
if (dst_y < 0) {
height -= dst_y;
src_y -= dst_y;
dst_y = 0;
}
if (height <= 0) {
return false;
}
left = src_x + width - src_w;
if (left > 0) {
width -= left;
}
left = dst_x + width - dst_w;
if (left > 0) {
width -= left;
}
if (width <= 0) {
return false;
}
left = src_y + height - src_h;
if (left > 0) {
height -= left;
}
left = dst_y + height - dst_h;
if (left > 0) {
height -= left;
}
if (height <= 0) {
return false;
}
// Init
line_stride = (size_t) (width * 4);
src_stride = src_w * 4;
src_pos = src_y * src_stride + src_x * 4;
dst_pos = 0;
dst_blank_length = (size_t) (dst_y * dst_w + dst_x) * 4;
// Fill start blank if necessary
if (fill_blank) {
memset_int((int *) (dst + dst_pos), color, dst_blank_length / 4);
}
// First line
dst_pos += dst_blank_length;
memcpy(dst + dst_pos, src + src_pos, line_stride);
dst_pos += line_stride;
src_pos += src_stride;
// Other lines
dst_blank_length = (size_t) ((dst_w - width) * 4);
for (line = 1; line < height; line++) {
if (fill_blank) {
memset_int((int *) (dst + dst_pos), color, dst_blank_length / 4);
}
dst_pos += dst_blank_length;
memcpy(dst + dst_pos, src + src_pos, line_stride);
dst_pos += line_stride;
src_pos += src_stride;
}
// Fill left blank if necessary
if (fill_blank) {
memset_int((int *) (dst + dst_pos), color, (size_t) (dst_w * dst_h * 4 - dst_pos) / 4);
}
return true;
}
void copy_pixels(const void* src, int src_w, int src_h, int src_x, int src_y,
void* dst, int dst_w, int dst_h, int dst_x, int dst_y,
int width, int height, bool fill_blank, int default_color)
{
int color = 0;
if (fill_blank) {
color = convert_color(default_color);
}
if (!copy_pixels_internal(src, src_w, src_h, src_x, src_y, dst, dst_w, dst_h, dst_x,
dst_y, width, height, fill_blank, color) && fill_blank) {
memset_int(dst, color, (size_t) (dst_w * dst_h));
}
}
-14
View File
@@ -1,14 +0,0 @@
//
// Created by Hippo on 12/27/2015.
//
#ifndef IMAGE_IMAGE_UTILS_H
#define IMAGE_IMAGE_UTILS_H
#include <stdbool.h>
void copy_pixels(const void* src, int src_w, int src_h, int src_x, int src_y,
void* dst, int dst_w, int dst_h, int dst_x, int dst_y,
int width, int height, bool fill_blank, int default_color);
#endif //IMAGE_IMAGE_UTILS_H
-220
View File
@@ -1,220 +0,0 @@
/*
* Copyright 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.
*/
//
// Created by Hippo on 12/27/2015.
//
#include <stdlib.h>
#include <android/bitmap.h>
#include <GLES2/gl2.h>
#include "java_wrapper.h"
#include "input_stream.h"
#include "image.h"
#include "../log.h"
static JavaVM* jvm;
static void* tile_buffer;
JNIEnv *get_env()
{
JNIEnv *env;
if ((*jvm)->AttachCurrentThread(jvm, &env, NULL) == JNI_OK) {
return env;
} else {
return NULL;
}
}
jobject create_image_object(JNIEnv* env, void* ptr, int format, int width, int height)
{
jclass image_clazz;
jmethodID constructor;
image_clazz = (*env)->FindClass(env, "com/hippo/image/Image");
constructor = (*env)->GetMethodID(env, image_clazz, "<init>", "(JIII)V");
if (constructor == 0) {
LOGE(MSG("Can't find Image object constructor"));
return NULL;
} else {
return (*env)->NewObject(env, image_clazz, constructor,
(jlong) (uintptr_t) ptr, (jint) format, (jint) width, (jint) height);
}
}
JNIEXPORT jobject JNICALL
Java_com_hippo_image_Image_nativeDecode(JNIEnv* env,
jclass clazz, jobject is, jboolean partially)
{
InputStream* input_stream;
int format;
void* image;
jobject image_object;
input_stream = create_input_stream(env, is);
if (input_stream == NULL) {
return NULL;
}
image = decode(env, input_stream, partially, &format);
if (image == NULL) {
return NULL;
}
image_object = create_image_object(env, image, format,
get_width(image, format), get_height(image, format));
if (image_object == NULL) {
recycle(image, format);
return NULL;
} else {
return image_object;
}
}
JNIEXPORT jboolean JNICALL
Java_com_hippo_image_Image_nativeComplete(JNIEnv* env,
jclass clazz, jlong ptr, jint format)
{
return (jboolean) complete((void*) (intptr_t) ptr, format);
}
JNIEXPORT jboolean JNICALL
Java_com_hippo_image_Image_nativeIsCompleted(JNIEnv* env,
jclass clazz, jlong ptr, jint format)
{
return (jboolean) is_completed((void*) (intptr_t) ptr, format);
}
JNIEXPORT void JNICALL
Java_com_hippo_image_Image_nativeRender(JNIEnv* env,
jclass clazz, jlong ptr, jint format,
jint src_x, jint src_y, jobject dst, jint dst_x, jint dst_y,
jint width, jint height, jboolean fill_blank, jint default_color)
{
AndroidBitmapInfo info;
void *pixels = NULL;
AndroidBitmap_getInfo(env, dst, &info);
AndroidBitmap_lockPixels(env, dst, &pixels);
if (pixels == NULL) {
LOGE(MSG("Can't lock bitmap pixels"));
return;
}
render((void*) (intptr_t) ptr, format, src_x, src_y,
pixels, info.width, info.height, dst_x, dst_y,
width, height, fill_blank, default_color);
AndroidBitmap_unlockPixels(env, dst);
return;
}
JNIEXPORT void JNICALL
Java_com_hippo_image_Image_nativeTexImage(JNIEnv* env,
jclass clazz, jlong ptr, jint format, jboolean init, jint tile_type,
jint offset_x, jint offset_y)
{
// Check tile_buffer NULL
if (NULL == tile_buffer) {
return;
}
// Get border size and tile size
int border_size;
int tile_size;
switch (tile_type) {
case IMAGE_TILE_TYPE_SMALL:
border_size = IMAGE_SMALL_TILE_BORDER_SIZE;
tile_size = IMAGE_SMALL_TILE_SIZE;
break;
case IMAGE_TILE_TYPE_LARGE:
border_size = IMAGE_LARGE_TILE_BORDER_SIZE;
tile_size = IMAGE_LARGE_TILE_SIZE;
break;
default:
return;
}
render((void*) (intptr_t) ptr, format,
offset_x - border_size, offset_y - border_size,
tile_buffer, tile_size, tile_size, 0, 0,
tile_size, tile_size, true, 0);
if (init) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tile_size, tile_size,
0, GL_RGBA, GL_UNSIGNED_BYTE, tile_buffer);
} else {
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, tile_size, tile_size,
GL_RGBA, GL_UNSIGNED_BYTE, tile_buffer);
}
}
JNIEXPORT void JNICALL
Java_com_hippo_image_Image_nativeAdvance(JNIEnv* env,
jclass clazz, jlong ptr, jint format)
{
advance((void*) (intptr_t) ptr, format);
}
JNIEXPORT jint JNICALL
Java_com_hippo_image_Image_nativeGetDelay(JNIEnv* env,
jclass clazz, jlong ptr, jint format)
{
return (jint) get_delay((void*) (intptr_t) ptr, format);
}
JNIEXPORT jint JNICALL
Java_com_hippo_image_Image_nativeFrameCount(JNIEnv* env,
jclass clazz, jlong ptr, jint format)
{
return (jint) get_frame_count((void*) (intptr_t) ptr, format);
}
JNIEXPORT jboolean JNICALL
Java_com_hippo_image_Image_nativeIsOpaque(JNIEnv* env,
jclass clazz, jlong ptr, jint format)
{
return (jboolean) is_opaque((void*) (intptr_t) ptr, format);
}
JNIEXPORT void JNICALL
Java_com_hippo_image_Image_nativeRecycle(JNIEnv* env,
jclass clazz, jlong ptr, jint format)
{
recycle((void*) (intptr_t) ptr, format);
}
jint JNI_OnLoad(JavaVM *vm, void *reserved)
{
JNIEnv* env;
if ((*vm)->GetEnv(vm, (void**) (&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
jvm = vm;
tile_buffer = malloc(IMAGE_LARGE_TILE_SIZE * IMAGE_LARGE_TILE_SIZE * 4);
return JNI_VERSION_1_6;
}
void JNI_OnUnload(JavaVM *vm, void *reserved)
{
free(tile_buffer);
tile_buffer = NULL;
}
Loaded 100 of 391 files, more files were not shown because too many files have changed in this diff. Show more