Compare commits

...
69 Commits
Author SHA1 Message Date
seven332 4a7edf648b 1.0.11 2016-05-14 13:56:15 +08:00
seven332 cfc9411223 Clean up 2016-05-14 13:23:59 +08:00
seven332 05030e9bb6 Save separated memory information in crash file
app memory, app native memory, app max memory, system total memory
2016-05-14 12:54:38 +08:00
seven332 ab3fc7d842 Avoid create dir when loading thumb in download list 2016-05-14 12:45:02 +08:00
seven332 fb216a960b Lock drawer when suggestion list showing 2016-05-13 13:43:37 +08:00
seven332 c0fbdee61f Copy email address when click donate item 2016-05-13 02:12:10 +08:00
seven332 901c0ae3ec Disable zero rating to gallery 2016-05-12 14:53:46 +08:00
seven332 f727554afd Update libraries 2016-05-12 14:32:09 +08:00
seven332 b0a5666a6d Fix gallery restore
SpiderInfo has changed, but restore code was the old version
2016-05-12 01:22:31 +08:00
seven332 1edf98c9e1 1.0.10 2016-05-11 18:22:28 +08:00
seven332 32ed409a28 Update strings.xml 2016-05-10 17:09:46 +08:00
seven332 cac950fa40 Get ThumbDataContainer file in non-UI thread 2016-05-10 14:05:37 +08:00
seven332 3a03e9aad1 Change fab color
Primary fab is colorPrimary, secondary fab is colorAccent
2016-05-10 13:40:39 +08:00
seven332 971aa86c4e Set SpiderQueen.mMode to local 2016-05-10 02:10:23 +08:00
seven332 bbb5f89a66 Avoid mSpiderInfo null
Use AtomicReference for mSpiderInfo
2016-05-10 02:09:06 +08:00
seven332 f777b694d5 Add memory usage to crash file 2016-05-10 00:56:58 +08:00
seven332 d59fa1756e Use OSUtils 2016-05-10 00:46:00 +08:00
seven332 5ac9ad4d71 Upgrade yorozuya to 0.1.1 2016-05-10 00:40:51 +08:00
seven332 adb3860107 Upgrade libraries 2016-05-09 22:41:54 +08:00
seven332 81876955c6 Upgrade Yorozuya-Thread library to 0.1.1 2016-05-09 21:48:21 +08:00
seven332 b8189d76d6 Decode image partly 2016-05-09 18:47:03 +08:00
seven332 0a472d28b5 Add multi-thread support for image decoding 2016-05-09 00:40:25 +08:00
seven332 9a0ba6f676 Ensure notifyGetImageXXX called after pipe released 2016-05-08 15:52:47 +08:00
seven332 e22010f2b0 Update state at once when force request 2016-05-07 18:49:36 +08:00
seven332 5a2fe3fe19 Update beerbelly to 0.1.3 2016-05-07 18:48:44 +08:00
seven332 c9bbbca311 Set decoder thread priority to default
The priority of a decode thread was THREAD_PRIORITY_BACKGROUND. It may cause a long time waiting before image decoded.
2016-05-07 16:46:01 +08:00
seven332 83d66f9c56 Fix ptoken failed error
When get last page of gallery, the page preview count is not preview count pre page. So old version spider info file may store wrong preview count pre page. Spider info file version is added in the first line.
2016-05-07 15:51:47 +08:00
seven332 1feca40a5c Use System.nanoTime() to calculate frame delay compensation
Use System.nanoTime() instead of SystemClock.elapsedRealtime()
2016-05-07 14:17:10 +08:00
seven332 1bc07a89b8 Prepare for library upgrade 2016-05-07 14:09:03 +08:00
seven332 6c0ad0e329 Upgrade image library to 0.1.6 2016-05-07 14:03:20 +08:00
seven332 21151a5031 Fix FabLayout onClick
mExpanded blocked onClickPrimaryFab and onClickSecondaryFab before. But it should only block onClickSecondaryFab
2016-05-07 14:02:37 +08:00
seven332 74e10178be Fix default rating text 2016-05-05 22:56:43 +08:00
seven332 e289e83983 Update string.xml
Change unfavorited to not favorited
2016-05-05 01:06:33 +08:00
seven332 d07dc49dc7 Add cellular network warning 2016-05-05 01:05:00 +08:00
seven332 981598dc70 Fix some cookies missing in request 2016-05-04 23:50:29 +08:00
seven332 f82c576970 Update pd_big_weird_face 2016-05-04 21:18:24 +08:00
seven332 a0f1e97332 Upgrade image library to 0.1.5 2016-05-04 15:51:00 +08:00
seven332 2dca63b342 Avoid call fab on click listener when not expanded 2016-05-03 21:35:23 +08:00
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
397 changed files with 3719 additions and 130532 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
+42 -51
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 64
versionName "1.0.11"
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,47 @@ 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.seven332:drawerLayout:0.1.0'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.github.amlcurran.showcaseview:library:5.4.3'
compile 'com.github.seven332:animator:0.1.0'
compile 'com.github.seven332:beerbelly:0.1.4'
compile 'com.github.seven332:conaco:0.1.5-eh'
compile 'com.github.seven332:drawerlayout:0.1.0'
compile 'com.github.seven332:easyrecyclerview:0.1.0'
compile 'com.github.seven332:hotspot:0.1.0'
compile 'com.github.seven332:image:0.1.7-jpeg-png-gif'
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:0.1.1'
compile 'com.github.seven332:yorozuya-thread:0.1.1'
compile 'com.github.seven332:yorozuya-collect:0.1.4'
compile 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.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.
-36
View File
@@ -67,44 +67,8 @@
<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.GalleryActivity"
android:configChanges="screenSize|uiMode"
@@ -37,7 +37,7 @@ import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
public class AppCompatPreferenceActivity extends PreferenceActivity implements AppCompatCallback,
public abstract class AppCompatPreferenceActivity extends PreferenceActivity implements AppCompatCallback,
TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider {
private AppCompatDelegate mDelegate;
@@ -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
@@ -21,12 +21,15 @@ import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Debug;
import android.support.annotation.NonNull;
import com.hippo.scene.StageActivity;
import com.hippo.util.PackageUtils;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.OSUtils;
import java.io.File;
import java.io.FileInputStream;
@@ -35,7 +38,8 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
public class Crash {
public final class Crash {
private Crash() {}
@NonNull
private static String avoidNull(String str) {
@@ -107,6 +111,10 @@ public class Crash {
fw.write("INCREMENTAL=");fw.write(Build.VERSION.INCREMENTAL);fw.write("\r\n");
fw.write("RELEASE=");fw.write(Build.VERSION.RELEASE);fw.write("\r\n");
fw.write("SDK=");fw.write(Integer.toString(Build.VERSION.SDK_INT));fw.write("\r\n");
fw.write("MEMORY=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getAppAllocatedMemory(), false));fw.write("\r\n");
fw.write("MEMORY_NATIVE=");fw.write(FileUtils.humanReadableByteCount(Debug.getNativeHeapAllocatedSize(), false));fw.write("\r\n");
fw.write("MEMORY_MAX=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getAppMaxMemory(), false));fw.write("\r\n");
fw.write("MEMORY_TOTAL=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getTotalMemory(), false));fw.write("\r\n");
fw.write("\r\n");
}
@@ -17,20 +17,16 @@
package com.hippo.ehviewer;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Debug;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.LruCache;
import android.util.Log;
import com.github.anrwatchdog.ANRError;
import com.github.anrwatchdog.ANRWatchDog;
import com.hippo.beerbelly.SimpleDiskCache;
import com.hippo.conaco.Conaco;
import com.hippo.ehviewer.client.EhClient;
@@ -41,6 +37,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;
@@ -50,6 +48,7 @@ import com.hippo.util.BitmapUtils;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IntIdGenerator;
import com.hippo.yorozuya.OSUtils;
import com.hippo.yorozuya.SimpleHandler;
import java.io.File;
@@ -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,33 +272,30 @@ 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) {
final ActivityManager activityManager = (ActivityManager) context.
getSystemService(Context.ACTIVITY_SERVICE);
return Math.min(20 * 1024 * 1024,
Math.round(0.2f * activityManager.getMemoryClass() * 1024 * 1024));
private static int getMemoryCacheMaxSize() {
return Math.min(20 * 1024 * 1024, (int) OSUtils.getAppMaxMemory());
}
@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.memoryCacheMaxSize = getMemoryCacheMaxSize();
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,25 @@
package com.hippo.ehviewer;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.conaco.ValueHelper;
import com.hippo.conaco.ValueHolder;
import com.hippo.yorozuya.io.InputStreamPipe;
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());
return ImageBitmap.decode(isPipe.open());
} catch (OutOfMemoryError e) {
return null;
} catch (IOException e) {
@@ -46,15 +46,27 @@ 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 /* value.getByteCount() TODO Update Image */;
}
@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
/* value.getByteCount() <= MAX_CACHE_BYTE_COUNT TODO Update Image */;
} 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;
@@ -394,6 +412,13 @@ public class Settings {
putString(KEY_HATH_PASSKEY, value);
}
private static final String KEY_CELLULAR_NETWORK_WARNING = "cellular_network_warning";
private static final boolean DEFAULT_CELLULAR_NETWORK_WARNING = false;
public static boolean getCellularNetworkWarning() {
return getBoolean(KEY_CELLULAR_NETWORK_WARNING, DEFAULT_CELLULAR_NETWORK_WARNING);
}
/********************
****** Read
********************/
@@ -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,11 +21,14 @@ 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.glrenderer.ImageWrapper;
import com.hippo.gl.view.GLRoot;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.ConcurrentPool;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.OSUtils;
import java.lang.annotation.Retention;
@@ -48,6 +51,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 +68,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 +146,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 +159,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 +197,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 +205,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 +246,32 @@ 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;
public ImageCache() {
super((int) MathUtils.clamp(OSUtils.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.gl.glrenderer.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;
@@ -206,6 +206,7 @@ public class ImageView extends GLView implements ImageTexture.Callback {
// Remove callback
if (mImageTexture != null) {
mImageTexture.setCallback(null);
mImageTexture.stop();
}
int oldTextureWidth = mTextureWidth;
@@ -229,6 +230,7 @@ public class ImageView extends GLView implements ImageTexture.Callback {
getValidRect(mValidRect);
if (!mValidRect.isEmpty()) {
startAnimation(mAlphaAnimation, true);
mImageTexture.start();
}
} else {
mTextureWidth = 1;
@@ -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();
@@ -31,6 +31,7 @@ import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhEngine;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.ehviewer.spider.SpiderInfo;
import com.hippo.ehviewer.spider.SpiderQueen;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.IOUtils;
@@ -88,13 +89,12 @@ public class RestoreDownloadPreference extends TaskPreference {
InputStream is = null;
try {
is = siFile.openInputStream();
// Skip start page
IOUtils.readAsciiLine(is);
long gid = Long.parseLong(IOUtils.readAsciiLine(is));
SpiderInfo spiderInfo = SpiderInfo.read(is);
long gid = spiderInfo.gid;
if (mManager.containDownloadInfo(gid)) {
return null;
}
String token = IOUtils.readAsciiLine(is);
String token = spiderInfo.token;
RestoreItem restoreItem = new RestoreItem();
restoreItem.gid = gid;
restoreItem.token = token;
@@ -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;
@@ -24,6 +24,7 @@ import android.util.SparseArray;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.NumberUtils;
import java.io.IOException;
import java.io.InputStream;
@@ -34,16 +35,18 @@ public class SpiderInfo {
private static final String TAG = SpiderInfo.class.getSimpleName();
private static final String VERSION_STR = "VERSION";
private static final int VERSION = 2;
static final String TOKEN_FAILED = "failed";
int startPage = 0;
long gid = -1;
String token = null;
int pages = -1;
int previewPages = -1;
int previewPerPage = -1;
SparseArray<String> pTokenMap = null;
public int startPage = 0;
public long gid = -1;
public String token = null;
public int pages = -1;
public int previewPages = -1;
public int previewPerPage = -1;
public SparseArray<String> pTokenMap = null;
public static SpiderInfo read(@Nullable UniFile file) {
if (file == null) {
@@ -80,6 +83,17 @@ public class SpiderInfo {
return startPage >= 0 ? startPage : 0;
}
private static int getVersion(String str) {
if (null == str) {
return -1;
}
if (str.startsWith(VERSION_STR)) {
return NumberUtils.parseIntSafely(str.substring(VERSION_STR.length()), -1);
} else {
return 1;
}
}
@SuppressWarnings("InfiniteLoopStatement")
public static SpiderInfo read(@Nullable InputStream is) {
if (null == is) {
@@ -89,8 +103,20 @@ public class SpiderInfo {
SpiderInfo spiderInfo = null;
try {
spiderInfo = new SpiderInfo();
// Get version
String line = IOUtils.readAsciiLine(is);
int version = getVersion(line);
if (version == VERSION) {
// Read next line
line = IOUtils.readAsciiLine(is);
} else if (version == 1) {
// pass
} else {
// Invalid version
return null;
}
// Start page
spiderInfo.startPage = getStartPage(IOUtils.readAsciiLine(is));
spiderInfo.startPage = getStartPage(line);
// Gid
spiderInfo.gid = Long.parseLong(IOUtils.readAsciiLine(is));
// Token
@@ -100,7 +126,12 @@ public class SpiderInfo {
// Preview pages
spiderInfo.previewPages = Integer.parseInt(IOUtils.readAsciiLine(is));
// Preview pre page
spiderInfo.previewPerPage = Integer.parseInt(IOUtils.readAsciiLine(is));
line = IOUtils.readAsciiLine(is);
if (version == 1) {
// Skip it
} else {
spiderInfo.previewPerPage = Integer.parseInt(line);
}
// Pages
spiderInfo.pages = Integer.parseInt(IOUtils.readAsciiLine(is));
// Check pages
@@ -110,7 +141,7 @@ public class SpiderInfo {
// PToken
spiderInfo.pTokenMap = new SparseArray<>(spiderInfo.pages);
while (true) { // EOFException will raise
String line = IOUtils.readAsciiLine(is);
line = IOUtils.readAsciiLine(is);
int pos = line.indexOf(" ");
if (pos > 0 || pos < line.length() - 1) {
int index = Integer.parseInt(line.substring(0, pos));
@@ -127,7 +158,6 @@ public class SpiderInfo {
}
if (spiderInfo == null || spiderInfo.gid == -1 || spiderInfo.token == null ||
spiderInfo.previewPages == -1 || spiderInfo.previewPerPage == -1 ||
spiderInfo.pages == -1 || spiderInfo.pTokenMap == null) {
return null;
} else {
@@ -139,6 +169,9 @@ public class SpiderInfo {
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(os);
writer.write(VERSION_STR);
writer.write(Integer.toString(VERSION));
writer.write("\n");
writer.write(String.format("%08x", startPage >= 0 ? startPage : 0)); // Avoid negative
writer.write("\n");
writer.write(Long.toString(gid));
@@ -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;
@@ -77,6 +77,7 @@ import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.Call;
import okhttp3.OkHttpClient;
@@ -84,11 +85,12 @@ import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class SpiderQueen implements Runnable {
public final class SpiderQueen implements Runnable {
private static final String TAG = SpiderQueen.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
private static final boolean DEBUG_LOG = false;
private static final boolean DEBUG_PTOKEN = true;
@IntDef({MODE_READ, MODE_DOWNLOAD})
@Retention(RetentionPolicy.SOURCE)
@@ -106,6 +108,8 @@ public class SpiderQueen implements Runnable {
public static final int STATE_FINISHED = 2;
public static final int STATE_FAILED = 3;
public static final int DECODE_THREAD_NUM = 1;
public static final String SPIDER_INFO_FILENAME = ".ehviewer";
private static final String[] URL_509_SUFFIX_ARRAY = {
@@ -126,25 +130,22 @@ public class SpiderQueen implements Runnable {
private int mReadReference = 0;
private int mDownloadReference = 0;
@Mode
private int mMode;
// It mQueenThread is null, failed or stopped
@Nullable
private volatile Thread mQueenThread;
private final Object mQueenLock = new Object();
@Nullable
private Thread mDecoderThread;
private final Thread[] mDecodeThreadArray = new Thread[DECODE_THREAD_NUM];
private final int[] mDecodeIndexArray = new int[DECODE_THREAD_NUM];
private final Stack<Integer> mDecodeRequestStack = new Stack<>();
private final AtomicInteger mDecodingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
private final Object mWorkerLock = new Object();
private ThreadPoolExecutor mWorkerPoolExecutor;
private int mWorkerCount;
private final Object mPTokenLock = new Object();
private volatile SpiderInfo mSpiderInfo;
private final AtomicReference<SpiderInfo> mSpiderInfo = new AtomicReference<>();
private final Queue<Integer> mRequestPTokenQueue = new ConcurrentLinkedQueue<>();
private final Object mPageStateLock = new Object();
@@ -181,6 +182,10 @@ public class SpiderQueen implements Runnable {
mWorkerMaxCount = MathUtils.clamp(Settings.getMultiThreadDownload(), 1, 10);
mPreloadNumber = MathUtils.clamp(Settings.getPreloadImage(), 0, 100);
for (int i = 0; i < DECODE_THREAD_NUM; i++) {
mDecodeIndexArray[i] = GalleryPageView.INVALID_INDEX;
}
mWorkerPoolExecutor = new ThreadPoolExecutor(mWorkerMaxCount, mWorkerMaxCount,
0, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(),
new PriorityThreadFactory(SpiderWorker.class.getSimpleName(), Process.THREAD_PRIORITY_BACKGROUND));
@@ -270,6 +275,9 @@ public class SpiderQueen implements Runnable {
}
private void notifyGetImageFailure(int index, String error) {
if (error == null) {
error = GetText.getString(R.string.error_unknown);
}
synchronized (mSpiderListeners) {
for (OnSpiderListener listener : mSpiderListeners) {
listener.onGetImageFailure(index, error);
@@ -312,18 +320,19 @@ public class SpiderQueen implements Runnable {
}
private void updateMode() {
int mode;
if (mDownloadReference > 0) {
mMode = MODE_DOWNLOAD;
mode = MODE_DOWNLOAD;
} else {
mMode = MODE_READ;
mode = MODE_READ;
}
mSpiderDen.setMode(mMode);
mSpiderDen.setMode(mode);
// Update download page
boolean intoDownloadMode = false;
synchronized (mRequestPageQueue) {
if (mMode == MODE_DOWNLOAD) {
if (mode == MODE_DOWNLOAD) {
if (mDownloadPage < 0) {
mDownloadPage = 0;
intoDownloadMode = true;
@@ -482,6 +491,8 @@ public class SpiderQueen implements Runnable {
// Fix state for force
if (force && (state == STATE_FINISHED || state == STATE_FAILED)) {
// Update state to none at once
updatePageState(index, STATE_NONE);
state = STATE_NONE;
}
@@ -532,7 +543,7 @@ public class SpiderQueen implements Runnable {
break;
case STATE_FINISHED:
synchronized (mDecodeRequestStack) {
if (!mDecodeRequestStack.contains(index) && index != mDecodingIndex.get()) {
if (!contain(mDecodeIndexArray, index) && !mDecodeRequestStack.contains(index)) {
mDecodeRequestStack.add(index);
mDecodeRequestStack.notify();
}
@@ -546,6 +557,15 @@ public class SpiderQueen implements Runnable {
return result;
}
public static boolean contain(int[] array, int value) {
for (int v: array) {
if (v == value) {
return true;
}
}
return false;
}
private void ensureWorkers() {
synchronized (mWorkerLock) {
if (null == mWorkerPoolExecutor) {
@@ -626,21 +646,23 @@ public class SpiderQueen implements Runnable {
}
public int getStartPage() {
mSpiderInfo = readSpiderInfoFromLocal();
if (mSpiderInfo != null) {
return mSpiderInfo.startPage;
SpiderInfo spiderInfo = readSpiderInfoFromLocal();
if (spiderInfo != null) {
mSpiderInfo.lazySet(spiderInfo);
return spiderInfo.startPage;
} else {
return 0;
}
}
public void putStartPage(int page) {
if (mSpiderInfo != null) {
mSpiderInfo.startPage = page;
final SpiderInfo spiderInfo = mSpiderInfo.get();
if (spiderInfo != null) {
spiderInfo.startPage = page;
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
writeSpiderInfoToLocal(mSpiderInfo);
writeSpiderInfoToLocal(spiderInfo);
return null;
}
}.execute();
@@ -648,15 +670,16 @@ public class SpiderQueen implements Runnable {
}
private synchronized SpiderInfo readSpiderInfoFromLocal() {
if (null != mSpiderInfo) {
return mSpiderInfo;
SpiderInfo spiderInfo = mSpiderInfo.get();
if (spiderInfo != null) {
return spiderInfo;
}
// Read from download dir
UniFile downloadDir = mSpiderDen.getDownloadDir();
if (downloadDir != null) {
UniFile file = downloadDir.findFile(SPIDER_INFO_FILENAME);
SpiderInfo spiderInfo = SpiderInfo.read(file);
spiderInfo = SpiderInfo.read(file);
if (spiderInfo != null && spiderInfo.gid == mGalleryInfo.gid &&
spiderInfo.token.equals(mGalleryInfo.token)) {
return spiderInfo;
@@ -668,7 +691,7 @@ public class SpiderQueen implements Runnable {
if (null != pipe) {
try {
pipe.obtain();
SpiderInfo spiderInfo = SpiderInfo.read(pipe.open());
spiderInfo = SpiderInfo.read(pipe.open());
if (spiderInfo != null && spiderInfo.gid == mGalleryInfo.gid &&
spiderInfo.token.equals(mGalleryInfo.token)) {
return spiderInfo;
@@ -684,9 +707,16 @@ public class SpiderQueen implements Runnable {
return null;
}
private void readPreviews(String body, SpiderInfo spiderInfo) throws ParseException {
private void readPreviews(String body, int index, SpiderInfo spiderInfo) throws ParseException {
spiderInfo.pages = GalleryDetailParser.parsePages(body);
spiderInfo.previewPages = GalleryDetailParser.parsePreviewPages(body);
PreviewSet previewSet = GalleryDetailParser.parsePreviewSet(body);
spiderInfo.previewPerPage = previewSet.size();
if ((index >= 0 && index < spiderInfo.pages - 1) || (index == 0 && spiderInfo.pages == 1)) {
spiderInfo.previewPerPage = previewSet.size();
} else {
spiderInfo.previewPerPage = Math.max(spiderInfo.previewPerPage, previewSet.size());
}
for (int i = 0, n = previewSet.size(); i < n; i++) {
GalleryPageUrlParser.Result result = GalleryPageUrlParser.parse(previewSet.getPageUrlAt(i));
if (result != null) {
@@ -710,8 +740,7 @@ public class SpiderQueen implements Runnable {
spiderInfo.pages = GalleryDetailParser.parsePages(body);
spiderInfo.pTokenMap = new SparseArray<>(spiderInfo.pages);
spiderInfo.previewPages = GalleryDetailParser.parsePreviewPages(body);
readPreviews(body, spiderInfo);
readPreviews(body, 0, spiderInfo);
return spiderInfo;
} catch (Exception e) {
return null;
@@ -719,27 +748,37 @@ public class SpiderQueen implements Runnable {
}
private String getPTokenFromInternet(int index, EhConfig config) {
SpiderInfo spiderInfo = mSpiderInfo.get();
if (spiderInfo == null) {
return null;
}
// Check previewIndex
int previewIndex = index / mSpiderInfo.previewPerPage;
int previewIndex;
if (spiderInfo.previewPerPage >= 0) {
previewIndex = index / spiderInfo.previewPerPage;
} else {
previewIndex = 0;
}
try {
String url = EhUrl.getGalleryDetailUrl(
mGalleryInfo.gid, mGalleryInfo.token, previewIndex, false);
if (DEBUG_LOG) {
Log.d(TAG, url);
if (DEBUG_PTOKEN) {
Log.d(TAG, "index " + index + ", previewIndex " + previewIndex +
", previewPerPage " + spiderInfo.previewPerPage+ ", url " + url);
}
Request request = new EhRequestBuilder(url, config).build();
Response response = mHttpClient.newCall(request).execute();
String body = response.body().string();
mSpiderInfo.previewPages = GalleryDetailParser.parsePreviewPages(body);
readPreviews(body, mSpiderInfo);
readPreviews(body, previewIndex, spiderInfo);
// Save to local
writeSpiderInfoToLocal(mSpiderInfo);
writeSpiderInfoToLocal(spiderInfo);
String pToken;
synchronized (mPTokenLock) {
pToken = mSpiderInfo.pTokenMap.get(index);
pToken = spiderInfo.pTokenMap.get(index);
}
return pToken;
} catch (Exception e) {
@@ -795,7 +834,7 @@ public class SpiderQueen implements Runnable {
if (spiderInfo == null) {
return;
}
mSpiderInfo = spiderInfo;
mSpiderInfo.lazySet(spiderInfo);
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
@@ -821,11 +860,13 @@ public class SpiderQueen implements Runnable {
// Ensure worker
tryToEnsureWorkers();
// Start spider decoder
Thread decoderThread = new PriorityThread(new SpiderDecoder(), "SpiderDecoder-" + sIdGenerator.incrementAndGet(),
Process.THREAD_PRIORITY_BACKGROUND);
mDecoderThread = decoderThread;
decoderThread.start();
// Start decoder
for (int i = 0; i < DECODE_THREAD_NUM; i++) {
Thread decoderThread = new PriorityThread(new SpiderDecoder(i),
"SpiderDecoder-" + i, Process.THREAD_PRIORITY_DEFAULT);
mDecodeThreadArray[i] = decoderThread;
decoderThread.start();
}
// handle pToken request
while (!Thread.currentThread().isInterrupted()) {
@@ -866,7 +907,7 @@ public class SpiderQueen implements Runnable {
if (null == pToken) {
// If failed, set the pToken "failed"
synchronized (mPTokenLock) {
mSpiderInfo.pTokenMap.put(index, SpiderInfo.TOKEN_FAILED);
spiderInfo.pTokenMap.put(index, SpiderInfo.TOKEN_FAILED);
}
}
@@ -889,9 +930,10 @@ public class SpiderQueen implements Runnable {
mQueenThread = null;
// Interrupt decoder
Thread decoderThread = mDecoderThread;
if (decoderThread != null) {
decoderThread.interrupt();
for (Thread decoderThread : mDecodeThreadArray) {
if (decoderThread != null) {
decoderThread.interrupt();
}
}
// Interrupt all workers
@@ -1125,6 +1167,11 @@ public class SpiderQueen implements Runnable {
// false for stop
private boolean runInternal() {
SpiderInfo spiderInfo = mSpiderInfo.get();
if (spiderInfo == null) {
return false;
}
int size = mPageStateArray.length;
// Get request index
@@ -1174,10 +1221,10 @@ public class SpiderQueen implements Runnable {
// Clear TOKEN_FAILED for force request
if (force) {
synchronized (mPTokenLock) {
int i = mSpiderInfo.pTokenMap.indexOfKey(index);
String pToken = mSpiderInfo.pTokenMap.valueAt(i);
int i = spiderInfo.pTokenMap.indexOfKey(index);
String pToken = spiderInfo.pTokenMap.valueAt(i);
if (SpiderInfo.TOKEN_FAILED.equals(pToken)) {
mSpiderInfo.pTokenMap.remove(i);
spiderInfo.pTokenMap.remove(i);
}
}
}
@@ -1186,7 +1233,7 @@ public class SpiderQueen implements Runnable {
// Get token
while (!Thread.currentThread().isInterrupted()) {
synchronized (mPTokenLock) {
pToken = mSpiderInfo.pTokenMap.get(index);
pToken = spiderInfo.pTokenMap.get(index);
}
if (pToken == null) {
mRequestPTokenQueue.add(index);
@@ -1260,6 +1307,18 @@ public class SpiderQueen implements Runnable {
private class SpiderDecoder implements Runnable {
private final int mThreadIndex;
public SpiderDecoder(int index) {
mThreadIndex = index;
}
private void resetDecodeIndex() {
synchronized (mDecodeRequestStack) {
mDecodeIndexArray[mThreadIndex] = GalleryPageView.INVALID_INDEX;
}
}
@Override
public void run() {
if (DEBUG_LOG) {
@@ -1279,19 +1338,19 @@ public class SpiderQueen implements Runnable {
continue;
}
index = mDecodeRequestStack.pop();
mDecodingIndex.lazySet(index);
mDecodeIndexArray[mThreadIndex] = index;
}
// Check index valid
if (index < 0 || index >= mPageStateArray.length) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
resetDecodeIndex();
notifyGetImageFailure(index, GetText.getString(R.string.error_out_of_range));
continue;
}
InputStreamPipe pipe = mSpiderDen.openInputStreamPipe(index);
if (pipe == null) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
resetDecodeIndex();
// Can't find the file, it might be removed from cache,
// Reset it state and request it
updatePageState(index, STATE_NONE, null);
@@ -1299,24 +1358,36 @@ public class SpiderQueen implements Runnable {
continue;
}
Image image = null;
String error = null;
InputStream is;
pipe.obtain();
try {
pipe.obtain();
// TODO how to keep stream open
Image image = Image.decode(pipe.open(), false);
if (image != null) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyGetImageSuccess(index, image);
} else {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyGetImageFailure(index, GetText.getString(R.string.error_decoding_failed));
}
is = new AutoCloseInputStream(pipe, pipe.open());
} catch (IOException e) {
mDecodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyGetImageFailure(index, GetText.getString(R.string.error_reading_failed));
} finally {
// Can't open pipe
error = GetText.getString(R.string.error_reading_failed);
is = null;
pipe.close();
pipe.release();
}
if (is != null) {
image = Image.decode(is, true);
if (image == null) {
error = GetText.getString(R.string.error_decoding_failed);
}
}
// Notify
if (image != null) {
notifyGetImageSuccess(index, image);
} else {
notifyGetImageFailure(index, error);
}
resetDecodeIndex();
}
if (DEBUG_LOG) {
@@ -1325,6 +1396,33 @@ public class SpiderQueen implements Runnable {
}
}
private class AutoCloseInputStream extends InputStream {
private final InputStreamPipe mPipe;
private final InputStream mIs;
public AutoCloseInputStream(InputStreamPipe pipe, InputStream is) {
mPipe = pipe;
mIs = is;
}
@Override
public int read() throws IOException {
return mIs.read();
}
@Override
public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {
return mIs.read(buffer, byteOffset, byteCount);
}
@Override
public void close() throws IOException {
mPipe.close();
mPipe.release();
}
}
public interface OnSpiderListener {
void onGetPages(int pages);
@@ -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 {}
@@ -24,7 +24,7 @@ import com.google.analytics.tracking.android.EasyTracker;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.Settings;
public class EhActivity extends AppCompatActivity {
public abstract class EhActivity extends AppCompatActivity {
private boolean mTrackStarted;
@@ -24,7 +24,7 @@ import com.hippo.app.AppCompatPreferenceActivity;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.Settings;
public class EhPreferenceActivity extends AppCompatPreferenceActivity {
public abstract class EhPreferenceActivity extends AppCompatPreferenceActivity {
private boolean mTrackStarted;
@@ -61,8 +61,8 @@ import com.hippo.ehviewer.gallery.gl.ImageView;
import com.hippo.ehviewer.widget.GalleryGuideView;
import com.hippo.ehviewer.widget.ReversibleSeekBar;
import com.hippo.gl.glrenderer.ImageTexture;
import com.hippo.gl.glrenderer.ImageWrapper;
import com.hippo.gl.view.GLRootView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.util.SystemUiHelper;
import com.hippo.widget.ColorView;
@@ -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);
@@ -20,6 +20,7 @@ import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
@@ -70,6 +71,7 @@ import com.hippo.ehviewer.ui.scene.WarningScene;
import com.hippo.ehviewer.ui.scene.WebViewSignInScene;
import com.hippo.ehviewer.widget.EhDrawerLayout;
import com.hippo.io.UniFileInputStreamPipe;
import com.hippo.network.Network;
import com.hippo.scene.Announcer;
import com.hippo.scene.SceneFragment;
import com.hippo.scene.StageActivity;
@@ -392,6 +394,9 @@ public final class MainActivity extends StageActivity
onInit();
CommonOperations.checkUpdate(this, false);
checkDownloadLocation();
if (Settings.getCellularNetworkWarning()) {
checkCellularNetwork();
}
} else {
onRestore(savedInstanceState);
}
@@ -410,6 +415,12 @@ public final class MainActivity extends StageActivity
.show();
}
private void checkCellularNetwork() {
if (Network.getActiveNetworkType(this) == ConnectivityManager.TYPE_MOBILE) {
showTip(R.string.cellular_network_warning, BaseScene.LENGTH_SHORT);
}
}
private void onInit() {
// Check permission
PermissionRequester.request(this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
@@ -26,7 +26,7 @@ import android.view.ViewGroup;
import com.hippo.ehviewer.R;
public class ToolbarActivity extends EhActivity {
public abstract class ToolbarActivity extends EhActivity {
@Override
public void setContentView(@LayoutRes int layoutResID) {
@@ -16,10 +16,14 @@
package com.hippo.ehviewer.ui.fragment;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
import com.hippo.ehviewer.Analytics;
import com.hippo.ehviewer.EhApplication;
@@ -75,6 +79,10 @@ public class AboutFragment extends PreferenceFragment
AppHelper.sendEmail(getActivity(), EhApplication.getDeveloperEmail(),
"About EhViewer", null);
} else if (KEY_DONATE.equals(key)) {
ClipboardManager cmb = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setPrimaryClip(ClipData.newPlainText(null, "seven332$163.com".replace('$', '@')));
Toast.makeText(getActivity(), R.string.settings_about_donate_toast, Toast.LENGTH_SHORT).show();
new AlertDialog.Builder(getActivity())
.setTitle(R.string.settings_about_donate)
.setMessage(getString(R.string.settings_about_donate_message).replace('$', '@'))
@@ -34,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,8 @@ public class DownloadsScene extends ToolbarScene
return;
}
DownloadInfo info = mList.get(position);
holder.thumb.load(EhCacheKeyFactory.getThumbKey(info.gid), info.thumb);
holder.thumb.load(EhCacheKeyFactory.getThumbKey(info.gid), info.thumb,
new ThumbDataContainer(info), true);
holder.title.setText(EhUtils.getSuitableTitle(info));
holder.uploader.setText(info.uploader);
holder.rating.setRating(info.rating);
@@ -1198,4 +1207,70 @@ public class DownloadsScene extends ToolbarScene
}
}
}
private class ThumbDataContainer implements DataContainer {
private final DownloadInfo mInfo;
@Nullable
private UniFile mFile;
public ThumbDataContainer(@NonNull DownloadInfo info) {
mInfo = info;
}
private void ensureFile() {
if (mFile == null) {
UniFile dir = SpiderDen.getGalleryDownloadDir(mInfo);
if (dir != null && dir.isDirectory()) {
mFile = dir.createFile(".thumb");
}
}
}
@Override
public boolean isEnabled() {
ensureFile();
return mFile != null;
}
@Override
public void onUrlMoved(String requestUrl, String responseUrl) {}
@Override
public boolean save(InputStream is, long length, String mediaType, ProgressNotifier notify) {
ensureFile();
if (mFile == null) {
return false;
}
OutputStream os = null;
try {
os = mFile.openOutputStream();
IOUtils.copy(is, os);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
IOUtils.closeQuietly(os);
}
}
@Override
public InputStreamPipe get() {
ensureFile();
if (mFile != null) {
return new UniFileInputStreamPipe(mFile);
} else {
return null;
}
}
@Override
public void remove() {
if (mFile != null) {
mFile.delete();
}
}
}
}
@@ -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,8 +96,9 @@ 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.ehviewer.widget.GalleryRatingBar;
import com.hippo.widget.SimpleGridAutoSpanLayout;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.IOUtils;
@@ -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));
@@ -912,12 +913,7 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
private static String getRatingText(float rating, Resources resources) {
String undefine = "(´_ゝ`)";
if (-1.0f == rating) {
return undefine;
}
int resId = 0;
int resId;
switch (Math.round(rating * 2)) {
case 0:
resId = R.string.rating0; break;
@@ -941,13 +937,11 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
resId = R.string.rating9; break;
case 10:
resId = R.string.rating10; break;
default:
resId = R.string.rating_none; break;
}
if (resId == 0) {
return undefine;
} else {
return resources.getString(resId);
}
return resources.getString(resId);
}
private String getAllRatingText(float rating, int ratingCount) {
@@ -1712,17 +1706,17 @@ public class GalleryDetailScene extends BaseScene implements View.OnClickListene
}
}
private class RateDialogHelper implements ProgressiveRatingBar.OnUserRateListener,
private class RateDialogHelper implements GalleryRatingBar.OnUserRateListener,
DialogInterface.OnClickListener {
@Nullable
private ProgressiveRatingBar mRatingBar;
private GalleryRatingBar mRatingBar;
@Nullable
private TextView mRatingText;
public void setDialog(Dialog dialog, float rating) {
mRatingText = (TextView) ViewUtils.$$(dialog, R.id.rating_text);
mRatingBar = (ProgressiveRatingBar) ViewUtils.$$(dialog, R.id.rating_view);
mRatingBar = (GalleryRatingBar) ViewUtils.$$(dialog, R.id.rating_view);
mRatingText.setText(getRatingText(rating, getResources2()));
mRatingBar.setRating(rating);
mRatingBar.setOnUserRateListener(this);
@@ -1192,6 +1192,14 @@ public final class GalleryListScene extends BaseScene
}
break;
}
if (newState == STATE_NORMAL || newState == STATE_SIMPLE_SEARCH) {
setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.LEFT);
setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT);
} else {
setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.LEFT);
setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
}
}
@Override
@@ -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));
@@ -1,11 +1,11 @@
/*
* Copyright (C) 2014 Hippo Seven
* Copyright 2014-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
* 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,
@@ -14,33 +14,44 @@
* limitations under the License.
*/
package com.hippo.widget;
package com.hippo.ehviewer.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.support.v7.widget.AppCompatRatingBar;
import android.util.AttributeSet;
import android.widget.RatingBar;
public class ProgressiveRatingBar extends AppCompatRatingBar {
public class GalleryRatingBar extends AppCompatRatingBar
implements RatingBar.OnRatingBarChangeListener {
private OnUserRateListener mListener;
public ProgressiveRatingBar(Context context) {
public GalleryRatingBar(Context context) {
super(context);
init();
}
public ProgressiveRatingBar(Context context, AttributeSet attrs) {
public GalleryRatingBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ProgressiveRatingBar(Context context, AttributeSet attrs,
public GalleryRatingBar(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setOnRatingBarChangeListener(this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isPressed() && mListener != null) {
if (mListener != null) {
mListener.onUserRate(getRating());
}
}
@@ -49,6 +60,13 @@ public class ProgressiveRatingBar extends AppCompatRatingBar {
mListener = l;
}
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
if (rating <= 0.0f) {
setRating(0.5f);
}
}
public interface OnUserRateListener {
void onUserRate(float rating);
}
@@ -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;
@@ -127,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;
@@ -33,6 +33,7 @@ import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
public class GLES20Canvas implements GLCanvas {
// ************** Constants **********************
@@ -166,7 +167,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 +177,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 +269,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 +280,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 +493,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 +870,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();
@@ -885,7 +886,7 @@ public class GLES20Canvas implements GLCanvas {
@Override
public void dumpStatisticsAndClear() {
String line = String.format("MESH:%d, TEX_RECT:%d, FILL_RECT:%d, LINE:%d", mCountDrawMesh,
String line = String.format(Locale.US, "MESH:%d, TEX_RECT:%d, FILL_RECT:%d, LINE:%d", mCountDrawMesh,
mCountTextureRect, mCountFillRect, mCountDrawLine);
mCountDrawMesh = 0;
mCountTextureRect = 0;
@@ -0,0 +1,209 @@
/*
* 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 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,89 @@
/*
* 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.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);
}
}
@@ -18,23 +18,25 @@ package com.hippo.gl.glrenderer;
import android.graphics.RectF;
import android.graphics.drawable.Animatable;
import android.os.Process;
import android.os.SystemClock;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import com.hippo.gl.annotation.RenderThread;
import com.hippo.gl.view.GLRoot;
import com.hippo.image.Image;
import com.hippo.yorozuya.PVLock;
import com.hippo.yorozuya.PriorityThreadFactory;
import com.hippo.yorozuya.thread.InfiniteThreadExecutor;
import com.hippo.yorozuya.thread.PVLock;
import com.hippo.yorozuya.thread.PriorityThreadFactory;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public class ImageTexture implements Texture, Animatable {
@@ -59,17 +61,17 @@ public class ImageTexture implements Texture, Animatable {
// In this 16ms, we use about 4~8 ms to upload tiles.
private static final long UPLOAD_TILE_LIMIT = 4; // ms
private static final PriorityThreadFactory sThreadFactory;
private static final Executor sThreadExecutor;
private static final PVLock sPVLock;
private static Tile sSmallFreeTileHead = null;
private static Tile sLargeFreeTileHead = null;
private static final Object sFreeTileLock = new Object();
private final Image mImage;
private 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;
@@ -77,16 +79,19 @@ public class ImageTexture implements Texture, Animatable {
private final RectF mSrcRect = new RectF();
private final RectF mDestRect = new RectF();
private final AtomicBoolean mFrameDirty = new AtomicBoolean();
private boolean mImageBusy = false;
private final AtomicBoolean mNeedRecycle = new AtomicBoolean();
private final AtomicBoolean mRunning = new AtomicBoolean();
private final AtomicBoolean mFrameDirty = new AtomicBoolean();
private final AtomicBoolean mNeedRelease = new AtomicBoolean();
private final AtomicBoolean mReleased = new AtomicBoolean();
private final AtomicReference<Thread> mAnimateThread = new AtomicReference<>();
private Runnable mAnimateRunnable = null;
private WeakReference<Callback> mCallback;
static {
sThreadFactory = new PriorityThreadFactory("ImageTexture$AnimateTask", android.os.Process.THREAD_PRIORITY_BACKGROUND);
sThreadExecutor = new InfiniteThreadExecutor(10 * 1000, new LinkedList<>(),
new PriorityThreadFactory("ImageTexture$AnimateTask", Process.THREAD_PRIORITY_BACKGROUND));
sPVLock = new PVLock(3);
}
@@ -142,7 +147,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;
@@ -172,7 +177,15 @@ public class ImageTexture implements Texture, Animatable {
@Override
protected void texImage(boolean init) {
if (image != null && !image.isRecycled()) {
image.texImage(init, mTileType, offsetX, offsetY);
int w, h;
if (init) {
w = mTextureWidth;
h = mTextureHeight;
} else {
w = mWidth;
h = mHeight;
}
image.texImage(init, offsetX - borderSize, offsetY - borderSize, w, h);
}
}
@@ -240,41 +253,29 @@ public class ImageTexture implements Texture, Animatable {
private class AnimateRunnable implements Runnable {
public void doRun() {
long lastTime = SystemClock.elapsedRealtime();
long lastTime = System.nanoTime();
long lastDelay = -1L;
synchronized (mImage) {
// Check recycled
if (mImage.isRecycled()) {
return;
}
// Check image busy
if (mImageBusy) {
// Image is busy, means it is recycling
return;
}
if (mNeedRecycle.get()) {
// Need recycle
// Check released, image busy, Need release
if (mReleased.get() || mImageBusy || mNeedRelease.get()) {
mAnimateRunnable = null;
return;
}
// Obtain image
mImageBusy = true;
}
boolean interrupted = Thread.currentThread().isInterrupted();
if (!mImage.isCompleted()) {
if (!interrupted) {
try {
sPVLock.p();
} catch (InterruptedException e) {
interrupted = true;
}
if (!interrupted && !mNeedRecycle.get()) {
mImage.complete();
}
sPVLock.v();
try {
sPVLock.p();
} catch (InterruptedException e) {
// Ignore
}
if (!mNeedRelease.get()) {
mImage.complete();
}
sPVLock.v();
}
int frameCount = mImage.getFrameCount();
@@ -282,26 +283,19 @@ public class ImageTexture implements Texture, Animatable {
synchronized (mImage) {
// Release image
mImageBusy = false;
// Check need release, frameCount <= 1
if (mNeedRelease.get() || frameCount <= 1) {
mAnimateRunnable = null;
return;
}
}
if (interrupted || mNeedRecycle.get() || frameCount <= 1) {
return;
}
while (!Thread.currentThread().isInterrupted()) {
for (;;) {
// Obtain
synchronized (mImage) {
// Check recycled
if (mImage.isRecycled()) {
return;
}
// Check image busy
if (mImageBusy) {
// Image is busy, means it is recycling
return;
}
if (mNeedRecycle.get()) {
// Need recycle
// Check released, image busy, Need release, not running
if (mReleased.get() || mImageBusy || mNeedRelease.get() || !mRunning.get()) {
mAnimateRunnable = null;
return;
}
// Obtain image
@@ -310,9 +304,9 @@ public class ImageTexture implements Texture, Animatable {
mImage.advance();
long delay = mImage.getDelay();
long time = SystemClock.elapsedRealtime();
long time = System.nanoTime();
if (-1L != lastDelay) {
delay -= (time - lastTime) - lastDelay;
delay -= (time - lastTime) / 1000000 - lastDelay;
}
lastTime = time;
lastDelay = delay;
@@ -328,7 +322,7 @@ public class ImageTexture implements Texture, Animatable {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
break;
// Ignore
}
}
}
@@ -338,11 +332,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,19 +348,21 @@ public class ImageTexture implements Texture, Animatable {
mImageBusy = true;
}
mImage.recycle();
mImage.release();
mReleased.lazySet(true);
synchronized (mImage) {
// Release image
mImageBusy = false;
}
}
mAnimateThread.lazySet(null);
}
}
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();
@@ -430,10 +426,10 @@ public class ImageTexture implements Texture, Animatable {
mTiles = list.toArray(new Tile[list.size()]);
if (!mImage.isCompleted() || mImage.getFrameCount() > 1) {
Thread thread = sThreadFactory.newThread(new AnimateRunnable());
mAnimateThread.lazySet(thread);
thread.start();
if (!mImage.isCompleted()) {
Runnable runnable = new AnimateRunnable();
mAnimateRunnable = runnable;
sThreadExecutor.execute(runnable);
}
}
@@ -457,33 +453,31 @@ public class ImageTexture implements Texture, Animatable {
@Override
public void start() {
if (mImage.isRecycled() || (mImage.isCompleted() && mImage.getFrameCount() <= 1)) {
if (mReleased.get() || mNeedRelease.get() || (mImage.isCompleted() && mImage.getFrameCount() <= 1) ||
mRunning.get()) {
return;
}
Thread thread = mAnimateThread.get();
if (thread == null) {
thread = sThreadFactory.newThread(new AnimateRunnable());
mAnimateThread.set(thread);
thread.start();
}
}
mRunning.lazySet(true);
@Override
public void stop() {
if (!mImage.isRecycled() && (mImage.isCompleted() && mImage.getFrameCount() > 1)) {
Thread thread = mAnimateThread.getAndSet(null);
if (null != thread) {
thread.interrupt();
synchronized (mImage) {
if (mAnimateRunnable == null) {
Runnable runnable = new AnimateRunnable();
mAnimateRunnable = runnable;
sThreadExecutor.execute(runnable);
}
}
}
@Override
public boolean isRunning() {
return false;
public void stop() {
mRunning.lazySet(false);
}
@Override
public boolean isRunning() {
return mRunning.get();
}
private boolean uploadNextTile(GLCanvas canvas) {
if (mUploadIndex == mTiles.length) return true;
@@ -650,33 +644,30 @@ public class ImageTexture implements Texture, Animatable {
}
public void recycle() {
mRunning.lazySet(false);
for (Tile mTile : mTiles) {
mTile.free();
}
boolean recycleNow;
boolean releaseNow;
synchronized (mImage) {
if (!mImageBusy) {
recycleNow = true;
releaseNow = true;
mImageBusy = true;
} else {
recycleNow = false;
releaseNow = false;
mNeedRelease.set(true);
}
}
if (recycleNow) {
mImage.recycle();
if (releaseNow) {
mImage.release();
mReleased.set(true);
synchronized (mImage) {
mImageBusy = false;
}
} else {
mNeedRecycle.set(true);
}
Thread thread = mAnimateThread.getAndSet(null);
if (null != thread) {
thread.interrupt();
}
}
@@ -0,0 +1,153 @@
/*
* 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.support.annotation.NonNull;
import com.hippo.image.Image;
/**
* A wrapper for {@link Image}. It is useful for multi-usage.
* It handles image recycle automatically.
*/
public class ImageWrapper {
private final Image mImage;
private int mReferences;
/**
* Create ImageWrapper
*
* @param image the image should not be obtained or recycled.
*/
public ImageWrapper(@NonNull Image image) {
mImage = image;
}
/**
* Obtain the image
*
* @return false for the image is recycled and obtain failed
*/
public synchronized boolean obtain() {
if (mImage.isRecycled()) {
return false;
} else {
++mReferences;
return true;
}
}
/**
* Release the image
*/
public synchronized void release() {
--mReferences;
if (mReferences <= 0 && !mImage.isRecycled()) {
mImage.recycle();
}
}
/**
* @see Image#getFormat()
*/
public int getFormat() {
return mImage.getFormat();
}
/**
* @see Image#getFormat()
*/
public int getWidth() {
return mImage.getWidth();
}
/**
* @see Image#getHeight()
*/
public int getHeight() {
return mImage.getHeight();
}
/**
* @see Image#complete()
*/
public boolean complete() {
synchronized (mImage) {
return mImage.complete();
}
}
/**
* @see Image#isCompleted()
*/
public boolean isCompleted() {
return mImage.isCompleted();
}
/**
* @see Image#render(int, int, Bitmap, int, int, int, int, boolean, int)
*/
public void render(int srcX, int srcY, Bitmap dst, int dstX, int dstY,
int width, int height, boolean fillBlank, int defaultColor) {
mImage.render(srcX, srcY, dst, dstX, dstY,
width, height, fillBlank, defaultColor);
}
/**
* @see Image#texImage(boolean, int, int, int, int)
*/
public void texImage(boolean init, int offsetX, int offsetY, int width, int height) {
mImage.texImage(init, offsetX, offsetY, width, height);
}
/**
* @see Image#advance()
*/
public void advance() {
mImage.advance();
}
/**
* @see Image#getDelay()
*/
public int getDelay() {
return mImage.getDelay();
}
/**
* @see Image#getFrameCount()
*/
public int getFrameCount() {
return mImage.getFrameCount();
}
/**
* @see Image#isOpaque()
*/
public boolean isOpaque() {
return mImage.isOpaque();
}
/**
* @see Image#isRecycled()
*/
public boolean isRecycled() {
return mImage.isRecycled();
}
}
@@ -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);
@@ -54,6 +54,7 @@ public abstract class NativeTexture extends BasicTexture {
GLES20.glBindTexture(getTarget(), mId);
checkError();
texImage(true);
checkError();
setAssociatedCanvas(canvas);
mState = STATE_LOADED;
@@ -68,6 +69,7 @@ public abstract class NativeTexture extends BasicTexture {
GLES20.glBindTexture(getTarget(), mId);
checkError();
texImage(false);
checkError();
mContentValid = true;
}
}
@@ -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 > 8) {
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) {
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.network;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public final class Network {
private Network() {}
public static int getActiveNetworkType(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
return activeNetwork.getType();
} else {
return -1;
}
}
}
@@ -216,7 +216,6 @@ public class CookieDBStore implements CookieJar {
List<CookieWithID> cookies = map.get(key);
// cookies can not be null
getInternal(url, cookies, result);
break;
}
}
@@ -21,7 +21,7 @@ import android.util.SparseArray;
import com.hippo.yorozuya.IntIdGenerator;
public class SceneApplication extends Application {
public abstract class SceneApplication extends Application {
private final IntIdGenerator mIdGenerator = new IntIdGenerator();
private final SparseArray<StageActivity> mStageMap = new SparseArray<>();
@@ -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;
@@ -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;
@@ -357,7 +357,7 @@ public class FabLayout extends ViewGroup implements View.OnClickListener {
int position = indexOfChild(v);
if (position == getChildCount() - 1) {
mOnClickFabListener.onClickPrimaryFab(this, (FloatingActionButton) v);
} else if (position >= 0) {
} else if (position >= 0 && mExpanded) {
mOnClickFabListener.onClickSecondaryFab(this, (FloatingActionButton) v, position);
}
}
@@ -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 if (mTaskId == Unikery.INVALID_ID) /* if (!mConaco.isLoading(mTaskId)) TODO Update Conaco */ {
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);
}
}
Loaded 100 of 397 files, more files were not shown because too many files have changed in this diff. Show more