Repository: NoireFHC/NHentai-android Branch: master Commit: 140f9ae64799 Files: 119 Total size: 346.6 KB Directory structure: gitextract_wd0zl69i/ ├── .gitignore ├── LICENSE ├── README.md ├── app/ │ ├── .gitignore │ ├── app-release.apk │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── assets/ │ │ └── licenses.html │ ├── java/ │ │ ├── moe/ │ │ │ └── feng/ │ │ │ └── nhentai/ │ │ │ ├── api/ │ │ │ │ ├── BookApi.java │ │ │ │ ├── PageApi.java │ │ │ │ └── common/ │ │ │ │ └── NHentaiUrl.java │ │ │ ├── cache/ │ │ │ │ ├── common/ │ │ │ │ │ └── Constants.java │ │ │ │ └── file/ │ │ │ │ ├── FileCacheManager.java │ │ │ │ └── OfflineDocumentManager.java │ │ │ ├── dao/ │ │ │ │ ├── CommonPreferences.java │ │ │ │ └── SearchHistoryManager.java │ │ │ ├── model/ │ │ │ │ ├── BaseMessage.java │ │ │ │ └── Book.java │ │ │ ├── ui/ │ │ │ │ ├── BookDetailsActivity.java │ │ │ │ ├── CategoryActivity.java │ │ │ │ ├── GalleryActivity.java │ │ │ │ ├── MainActivity.java │ │ │ │ ├── SearchResultActivity.java │ │ │ │ ├── SettingsActivity.java │ │ │ │ ├── adapter/ │ │ │ │ │ ├── BookListRecyclerAdapter.java │ │ │ │ │ ├── BookPreviewGridAdapter.java │ │ │ │ │ ├── GalleryPagerAdapter.java │ │ │ │ │ └── HomePagerAdapter.java │ │ │ │ ├── common/ │ │ │ │ │ ├── AbsActivity.java │ │ │ │ │ └── AbsRecyclerViewAdapter.java │ │ │ │ └── fragment/ │ │ │ │ ├── BookPageFragment.java │ │ │ │ ├── main/ │ │ │ │ │ ├── DownloadManagerFragment.java │ │ │ │ │ ├── FavoriteFragment.java │ │ │ │ │ └── HomeFragment.java │ │ │ │ └── settings/ │ │ │ │ ├── SettingsLicense.java │ │ │ │ └── SettingsMain.java │ │ │ ├── util/ │ │ │ │ ├── AsyncTask.java │ │ │ │ ├── ColorGenerator.java │ │ │ │ ├── FullScreenHelper.java │ │ │ │ ├── HttpTools.java │ │ │ │ ├── Settings.java │ │ │ │ ├── TextDrawable.java │ │ │ │ └── Utility.java │ │ │ └── view/ │ │ │ ├── AutoWrapLayout.java │ │ │ ├── ExpandableHeightGridView.java │ │ │ ├── WheelProgressView.java │ │ │ └── pref/ │ │ │ ├── Preference.java │ │ │ ├── SwitchPreference.java │ │ │ └── TwoStatePreference.java │ │ └── sumimakito/ │ │ └── android/ │ │ └── quickkv/ │ │ ├── DataProcessor.java │ │ ├── QKVConfig.java │ │ ├── QKVFSReader.java │ │ ├── QKVLogger.java │ │ ├── QuickKV.java │ │ ├── database/ │ │ │ ├── KeyValueDatabase.java │ │ │ └── QKVDatabase.java │ │ └── security/ │ │ └── AES256.java │ └── res/ │ ├── color/ │ │ └── drawer_item_color.xml │ ├── drawable/ │ │ ├── shadow_gradient.xml │ │ ├── shadow_gradient_reserve.xml │ │ ├── shadow_normal.xml │ │ └── shadow_normal_reserve.xml │ ├── layout/ │ │ ├── activity_book_details.xml │ │ ├── activity_gallery.xml │ │ ├── activity_main.xml │ │ ├── activity_search_result.xml │ │ ├── activity_settings.xml │ │ ├── custom_preference.xml │ │ ├── custom_preference_widget_switch.xml │ │ ├── fragment_book_page.xml │ │ ├── fragment_download.xml │ │ ├── fragment_favorite.xml │ │ ├── fragment_home.xml │ │ ├── list_item_book_card.xml │ │ ├── list_item_book_picture_thumb.xml │ │ ├── list_item_menu_row.xml │ │ └── navigation_header.xml │ ├── menu/ │ │ ├── menu_main.xml │ │ └── navigation_menu.xml │ ├── values/ │ │ ├── attrs.xml │ │ ├── color.xml │ │ ├── dimen.xml │ │ ├── strings.xml │ │ └── styles.xml │ ├── values-v21/ │ │ └── styles.xml │ ├── values-zh-rCN/ │ │ └── strings.xml │ ├── values-zh-rTW/ │ │ └── strings.xml │ └── xml/ │ └── settings_main.xml ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── libraries/ │ └── PersistentSearch/ │ ├── .gitignore │ ├── build.gradle │ ├── gradle.properties │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ ├── com/ │ │ │ ├── balysv/ │ │ │ │ └── materialmenu/ │ │ │ │ ├── MaterialMenu.java │ │ │ │ ├── MaterialMenuDrawable.java │ │ │ │ └── MaterialMenuView.java │ │ │ └── quinny898/ │ │ │ └── library/ │ │ │ └── persistentsearch/ │ │ │ ├── SearchBox.java │ │ │ └── SearchResult.java │ │ └── io/ │ │ └── codetail/ │ │ ├── animation/ │ │ │ ├── RevealAnimator.java │ │ │ ├── ReverseInterpolator.java │ │ │ ├── SupportAnimator.java │ │ │ ├── SupportAnimatorLollipop.java │ │ │ ├── SupportAnimatorPreL.java │ │ │ └── ViewAnimationUtils.java │ │ └── widget/ │ │ ├── RevealFrameLayout.java │ │ └── RevealLinearLayout.java │ └── res/ │ ├── anim/ │ │ └── anim_down.xml │ ├── layout/ │ │ ├── search_option.xml │ │ └── searchbox.xml │ └── values/ │ ├── strings.xml │ └── styles.xml └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .gradle /local.properties /.idea .DS_Store /build *.iml ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # NHBooks for Android ![NHBooksLogo](/art/nhbooks.png) a Material Design NHentai client for Android. 一枚 Material Design 風格的 NHentai Android 客戶端 ### 螢幕截圖 ![S0](/art/screenshot0.png) ![S1](/art/screenshot1.png) ## 軟體說明 該程式按照 Material Design 設計規範,提供簡潔、美觀的介面,並通過 API 從 NHentai 獲取本子,給你一個輕量、方便的客戶端。 ### 特別聲明 該應用程式所供應的內容不適合未成年人觀看,所有內容通過 Jsoup 解析 NHentai 官網獲得,內容有任何異議或造成心理甚至生理上的問題均與本項目無關。 觀看時請留意是否適用於當地法律法規。 ### 聯絡我 Google Plus: +Fung Jichun 新浪微博: @某燒餅 ### 支持項目 Alipay 支付寶: 316643843@qq.com ### License 開源協議 ``` GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2015 FengMoe Team This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. ``` ================================================ FILE: app/.gitignore ================================================ /build ================================================ FILE: app/build.gradle ================================================ apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "22.0.1" defaultConfig { applicationId "moe.feng.nhentai" minSdkVersion 15 targetSdkVersion 22 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile project(':libraries:PersistentSearch') compile 'com.android.support:support-v13:22.2.0' compile 'com.android.support:design:22.2.0' compile 'com.android.support:appcompat-v7:22.2.0' compile 'com.android.support:cardview-v7:22.2.0' compile 'com.android.support:recyclerview-v7:22.2.0' compile 'com.google.code.gson:gson:2.3.1' compile 'org.jsoup:jsoup:1.8.2' compile 'com.github.chrisbanes.photoview:library:1.2.3' compile 'com.squareup.picasso:picasso:2.5.2' compile ('com.github.florent37:materialimageloading:1.0.1@aar'){ transitive = true } } ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in E:\Feng\sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/assets/licenses.html ================================================

Notices for Additional Libraries

This app contains several libraries that are released under the terms of the following licenses.

Notices for files:

  • Android Support Library (v4, v7, v13, Design Support)
Copyright (C) 2013 The Android Open Source Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Notices for files:

  • QuickKV
Copyright 2014-2015 Sumi Makito

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. 

Notices for files:

  • Persistent Search
Copyright 2015 Kieron Quinn

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.

Notices for files:

  • Picasso
Copyright 2013 Square, Inc.

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.

Notices for files:

  • Gson
Copyright 2008 Google, Inc.

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.

Notices for files:

  • Jsoup
The MIT License

© 2009-2015, Jonathan Hedley 

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.

Notices for files:

  • PhotoView
Copyright 2011, 2012 Chris Banes

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.

Notices for files:

  • MaterialImageLoading
Copyright 2015 florent37, Inc.

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.
================================================ FILE: app/src/main/java/moe/feng/nhentai/api/BookApi.java ================================================ package moe.feng.nhentai.api; import android.content.Context; import android.graphics.Bitmap; import android.util.Log; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.IOException; import moe.feng.nhentai.api.common.NHentaiUrl; import moe.feng.nhentai.cache.file.FileCacheManager; import moe.feng.nhentai.model.BaseMessage; import moe.feng.nhentai.model.Book; import static moe.feng.nhentai.cache.common.Constants.CACHE_COVER; import static moe.feng.nhentai.cache.common.Constants.CACHE_PAGE_THUMB; import static moe.feng.nhentai.cache.common.Constants.CACHE_THUMB; public class BookApi { public static final String TAG = BookApi.class.getSimpleName(); public static BaseMessage getBook(String id) { BaseMessage result = new BaseMessage(); String url = NHentaiUrl.getBookDetailsUrl(id); Document doc; try { doc = Jsoup.connect(url).get(); } catch (IOException e) { result.setCode(403); e.printStackTrace(); return result; } Book book = new Book(); Elements info = doc.getElementsByAttributeValue("id", "info"); Element element = info.get(0); /** Get basic info */ book.title = element.getElementsByTag("h1").get(0).text(); try { book.titleJP = element.getElementsByTag("h2").get(0).text(); } catch (Exception e) { Log.v(TAG, "This book hasn\'t japanese name."); } book.bookId = id; /** Get tags */ Elements tags = doc.getElementsByClass("field-name"); for (Element r : tags) { if (r.text().contains("Parodies")) { String ts = r.getElementsByClass("tagbutton").get(0).text(); if (ts.contains("(")) { ts = ts.substring(0, ts.indexOf("(") - 1); } book.parodies = ts; } if (r.text().contains("Tags")) { for (Element e : r.getElementsByClass("tagbutton")) { String ts = e.text(); if (ts.contains("(")) { ts = ts.substring(0, ts.indexOf("(") - 1); } book.tags.add(ts); } } if (r.text().contains("Language")) { String ts = r.getElementsByClass("tagbutton").get(0).text(); if (ts.contains("(")) { ts = ts.substring(0, ts.indexOf("(") - 1); } book.language = ts; } if (r.text().contains("Groups")) { String ts = r.getElementsByClass("tagbutton").get(0).text(); if (ts.contains("(")) { ts = ts.substring(0, ts.indexOf("(") - 1); } book.group = ts; } if (r.text().contains("Artists")) { String ts = r.getElementsByClass("tagbutton").get(0).text(); if (ts.contains("(")) { ts = ts.substring(0, ts.indexOf("(") - 1); } book.artist = ts; } if (r.text().contains("Characters")) { for (Element e : r.getElementsByClass("tagbutton")) { String ts = e.text(); if (ts.contains("(")) { ts = ts.substring(0, ts.indexOf("(") - 1); } book.characters.add(ts); } } } /** Get page count */ String htmlSrc = element.html(); try { int position = htmlSrc.indexOf("pages"); String s = htmlSrc.substring(0, position); System.out.println(s); s = s.substring(s.lastIndexOf("
") + "
".length(), s.length()).trim(); System.out.println(s); book.pageCount = Integer.valueOf(s); } catch (Exception e) { } /** Get uploaded time */ try { Element timeElement = doc.getElementsByTag("time").get(0); book.uploadTime = timeElement.attr("datetime"); book.uploadTimeText = timeElement.text(); } catch (Exception e) { } /** Get gallery id and preview image url */ Element coverDiv = doc.getElementById("cover").getElementsByTag("a").get(0); for (Element e : coverDiv.getElementsByTag("img")) { try { Log.i(TAG, coverDiv.html()); String coverUrl = e.attr("src"); Log.i(TAG, coverUrl); coverUrl = coverUrl.substring(0, coverUrl.lastIndexOf("/")); String galleryId = coverUrl.substring(coverUrl.lastIndexOf("/") + 1, coverUrl.length()); book.galleryId = galleryId; book.previewImageUrl = NHentaiUrl.getThumbUrl(galleryId); book.bigCoverImageUrl = NHentaiUrl.getBigCoverUrl(galleryId); break; } catch (Exception ex) { ex.printStackTrace(); } } Log.i(TAG, book.toJSONString()); result.setCode(0); result.setData(book); return result; } public static Bitmap getCover(Context context, Book book) { String url = book.bigCoverImageUrl; FileCacheManager m = FileCacheManager.getInstance(context); if (!m.cacheExistsUrl(CACHE_COVER, url) && !m.createCacheFromNetwork(CACHE_COVER, url)) { return null; } return m.getBitmapUrl(CACHE_COVER, url); } public static Bitmap getThumb(Context context, Book book) { String url = book.previewImageUrl; FileCacheManager m = FileCacheManager.getInstance(context); if (!m.cacheExistsUrl(CACHE_THUMB, url) && !m.createCacheFromNetwork(CACHE_THUMB, url)) { return null; } return m.getBitmapUrl(CACHE_THUMB, url); } public static Bitmap getPageThumb(Context context, Book book, int position) { String url = NHentaiUrl.getThumbPictureUrl(book.galleryId, Integer.toString(position)); FileCacheManager m = FileCacheManager.getInstance(context); if (!m.cacheExistsUrl(CACHE_PAGE_THUMB, url) && !m.createCacheFromNetwork(CACHE_PAGE_THUMB, url)) { return null; } return m.getBitmapUrl(CACHE_PAGE_THUMB, url); } public static File getCoverFile(Context context, Book book) { String url = book.bigCoverImageUrl; FileCacheManager m = FileCacheManager.getInstance(context); if (!m.cacheExistsUrl(CACHE_COVER, url) && !m.createCacheFromNetwork(CACHE_COVER, url)) { return null; } return m.getBitmapUrlFile(CACHE_COVER, url); } public static File getThumbFile(Context context, Book book) { String url = book.previewImageUrl; FileCacheManager m = FileCacheManager.getInstance(context); if (!m.cacheExistsUrl(CACHE_THUMB, url) && !m.createCacheFromNetwork(CACHE_THUMB, url)) { return null; } return m.getBitmapUrlFile(CACHE_THUMB, url); } public static File getPageThumbFile(Context context, Book book, int position) { String url = NHentaiUrl.getThumbPictureUrl(book.galleryId, Integer.toString(position)); FileCacheManager m = FileCacheManager.getInstance(context); if (!m.cacheExistsUrl(CACHE_PAGE_THUMB, url) && !m.createCacheFromNetwork(CACHE_PAGE_THUMB, url)) { return null; } return m.getBitmapUrlFile(CACHE_PAGE_THUMB, url); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/api/PageApi.java ================================================ package moe.feng.nhentai.api; import android.content.Context; import android.graphics.Bitmap; import android.util.Log; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.IOException; import java.util.ArrayList; import moe.feng.nhentai.api.common.NHentaiUrl; import moe.feng.nhentai.cache.file.FileCacheManager; import moe.feng.nhentai.model.BaseMessage; import moe.feng.nhentai.model.Book; import static moe.feng.nhentai.cache.common.Constants.CACHE_PAGE_IMG; public class PageApi { public static final String TAG = PageApi.class.getSimpleName(); public static BaseMessage getPageList(String url) { BaseMessage result = new BaseMessage(); Document doc; try { doc = Jsoup.connect(url).get(); } catch (IOException e) { result.setCode(403); e.printStackTrace(); return result; } Elements container = doc.getElementsByClass("outer-preview-container"); ArrayList books = new ArrayList<>(); for (Element e : container) { Book book = new Book(); Element caption = e.getElementsByClass("caption").get(0); Element titleElement = caption.getElementsByTag("a").get(0); String bookId = titleElement.attr("href"); bookId = bookId.substring(0, bookId.lastIndexOf("/")); bookId = bookId.substring(bookId.lastIndexOf("/") + 1, bookId.length()); book.bookId = bookId; book.title = titleElement.text(); Elements imgs = e.getElementsByTag("img"); for (Element imge : imgs) { if (imge.hasAttr("src")) { String thumbUrl = imge.attr("src"); thumbUrl = thumbUrl.substring(0, thumbUrl.lastIndexOf("/")); String galleryId = thumbUrl.substring(thumbUrl.lastIndexOf("/") + 1, thumbUrl.length()); book.galleryId = galleryId; book.bigCoverImageUrl = NHentaiUrl.getBigCoverUrl(galleryId); book.previewImageUrl = NHentaiUrl.getThumbUrl(galleryId); try { book.thumbHeight = Integer.valueOf(imge.attr("height")); book.thumbWidth = Integer.valueOf(imge.attr("width")); } catch (Exception ex) { } } } if (book.bookId != null && !book.bookId.isEmpty()) { books.add(book); } Log.i(TAG, "Get book: " + book.toJSONString()); } result.setCode(0); result.setData(books); return result; } public static BaseMessage getHomePageList(int number) { return getPageList(NHentaiUrl.getHomePageUrl(number)); } public static BaseMessage getSearchPageList(String keyword, int number) { return getPageList(NHentaiUrl.getSearchUrl(keyword, number)); } public static Bitmap getPageOriginImage(Context context, Book book, int page_num) { String url = NHentaiUrl.getOriginPictureUrl(book.galleryId, String.valueOf(page_num)); FileCacheManager m = FileCacheManager.getInstance(context); if (!m.cacheExistsUrl(CACHE_PAGE_IMG, url) && !m.createCacheFromNetwork(CACHE_PAGE_IMG, url)) { return null; } return m.getBitmapUrl(CACHE_PAGE_IMG, url); } public static File getPageOriginImageFile(Context context, Book book, int page_num) { String url = NHentaiUrl.getOriginPictureUrl(book.galleryId, String.valueOf(page_num)); FileCacheManager m = FileCacheManager.getInstance(context); if (!m.cacheExistsUrl(CACHE_PAGE_IMG, url) && !m.createCacheFromNetwork(CACHE_PAGE_IMG, url)) { return null; } return m.getBitmapUrlFile(CACHE_PAGE_IMG, url); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/api/common/NHentaiUrl.java ================================================ package moe.feng.nhentai.api.common; public class NHentaiUrl { public static final String NHENTAI_HOME = "http://nhentai.net"; public static final String NHENTAI_I = "http://i.nhentai.net"; public static String getSearchUrl(String content) { return getSearchUrl(content, 1); } public static String getSearchUrl(String content, int page_num) { String targetContent = content; if (targetContent.contains(" ")) { targetContent = targetContent.replaceAll(" ", "+"); } return NHENTAI_HOME + "/search/?q=" + targetContent + "&page=" + page_num; } public static String getBookDetailsUrl(String book_id) { return NHENTAI_HOME + "/g/" + book_id; } public static String getBookPageUrl(String book_id, int page_num) { return getBookDetailsUrl(book_id) + "/" + page_num; } public static String getGalleryUrl(String g_id) { return NHENTAI_I + "/galleries/" + g_id; } public static String getOriginPictureUrl(String g_id, String page_num) { return getPictureUrl(g_id, page_num, "jpg"); } public static String getThumbPictureUrl(String g_id, String page_num) { return getPictureUrl(g_id, page_num + "t", "jpg"); } public static String getThumbUrl(String g_id) { return getPictureUrl(g_id, "thumb", "jpg"); } public static String getBigCoverUrl(String g_id) { // TODO Not all covers are jpgs return getPictureUrl(g_id, "cover", "jpg"); } public static String getPictureUrl(String g_id, String page_num, String file_type) { return getGalleryUrl(g_id) + "/" + page_num + "." + file_type; } public static String getParodyUrl(String name) { String targetName = name; if (targetName.contains(" ")) { targetName = targetName.replaceAll(" ", "-"); } return NHENTAI_HOME + "/parody/" + targetName; } public static String getCharacterUrl(String name) { String targetName = name; if (targetName.contains(" ")) { targetName = targetName.replaceAll(" ", "-"); } return NHENTAI_HOME + "/character/" + targetName; } public static String getTagUrl(String tag) { String targetTag = tag; if (targetTag.contains(" ")) { targetTag = targetTag.replaceAll(" ", "-"); } return NHENTAI_HOME + "/tagged/" + targetTag; } public static String getArtistUrl(String name) { String targetName = name; if (targetName.contains(" ")) { targetName = targetName.replaceAll(" ", "-"); } return NHENTAI_HOME + "/artist/" + targetName; } public static String getGroupUrl(String name) { String targetName = name; if (targetName.contains(" ")) { targetName = targetName.replaceAll(" ", "-"); } return NHENTAI_HOME + "/group/" + targetName; } public static String getLanguageUrl(String name) { String targetName = name; if (targetName.contains(" ")) { targetName = targetName.replaceAll(" ", "-"); } return NHENTAI_HOME + "/language/" + targetName; } public static String getHomePageUrl(int page) { return NHENTAI_HOME + "/?page=" + page; } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/cache/common/Constants.java ================================================ package moe.feng.nhentai.cache.common; public class Constants { public static final String CACHE_COVER = "cover", CACHE_PAGE_IMG = "pages", CACHE_PAGE_THUMB = "thumb", CACHE_THUMB = "thumb", CACHE_DOCUMENT = "document"; } ================================================ FILE: app/src/main/java/moe/feng/nhentai/cache/file/FileCacheManager.java ================================================ package moe.feng.nhentai.cache.file; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.net.URL; import java.net.HttpURLConnection; import java.net.MalformedURLException; import static moe.feng.nhentai.BuildConfig.DEBUG; public class FileCacheManager { private static final String TAG = FileCacheManager.class.getSimpleName(); private static FileCacheManager sInstance; private File mCacheDir; public static final FileCacheManager getInstance(Context context) { if (sInstance == null) { sInstance = new FileCacheManager(context); } return sInstance; } private FileCacheManager(Context context) { mCacheDir = context.getExternalCacheDir(); } public boolean createCacheFromNetwork(String type, String url) { if (DEBUG) { Log.d(TAG, "requesting cache from " + url); } URL u; try { u = new URL(url); } catch (MalformedURLException e) { return false; } HttpURLConnection conn; try { conn = (HttpURLConnection) u.openConnection(); } catch (IOException e) { return false; } conn.setConnectTimeout(5000); try { if (conn.getResponseCode() != 200) { if (url.contains("jpg")) { try { u = new URL(url.replace("jpg", "png")); } catch (MalformedURLException ex) { return false; } try { conn = (HttpURLConnection) u.openConnection(); } catch (IOException ex) { return false; } } else { return false; } } } catch (IOException e) { e.printStackTrace(); } try { return createCacheFromStrem(type, getCacheName(url), conn.getInputStream()); } catch (IOException e) { return false; } } public boolean createCacheFromStrem(String type, String name, InputStream stream) { File f = new File(getCachePath(type, name) + "_downloading"); f.getParentFile().mkdirs(); f.getParentFile().mkdir(); if (f.exists()) { f.delete(); } try { f.createNewFile(); } catch (IOException e) { return false; } FileOutputStream opt; try { opt = new FileOutputStream(f); } catch (FileNotFoundException e) { return false; } byte[] buf = new byte[512]; int len = 0; try { while ((len = stream.read(buf)) != -1) { opt.write(buf, 0, len); } } catch (IOException e) { return false; } try { stream.close(); opt.close(); } catch (IOException e) { } f.renameTo(new File(getCachePath(type, name))); return true; } // True if the cache downloaded from url exists public boolean cacheExistsUrl(String type, String url) { return cacheExists(type, getCacheName(url)); } public boolean cacheExists(String type, String name) { return new File(getCachePath(type, name)).isFile(); } public boolean deleteCacheUrl(String type, String url) { return deleteCache(type, getCacheName(url)); } public boolean deleteCache(String type, String name) { if (cacheExists(type, name)) { return new File(getCachePath(type, name)).delete(); } else { return false; } } public InputStream openCacheStream(String type, String name) { try { return new FileInputStream(new File(getCachePath(type, name))); } catch (IOException e) { return null; } } public InputStream openCacheStreamUrl(String type, String url) { return openCacheStream(type, getCacheName(url)); } public Bitmap getBitmap(String type, String name) { InputStream ipt = openCacheStream(type, name); if (ipt == null) return null; Bitmap ret = BitmapFactory.decodeStream(ipt); try { ipt.close(); } catch (IOException e) { } return ret; } public Bitmap getBitmapUrl(String type, String url) { return getBitmap(type, getCacheName(url)); } public File getBitmapFile(String type, String name) { return new File(getCachePath(type, name)); } public File getBitmapUrlFile(String type, String url) { return getBitmapFile(type, getCacheName(url)); } private String getCacheName(String url) { return url.replaceAll("/", ".").replaceAll(":", ""); } private String getCachePath(String type, String name) { return mCacheDir.getAbsolutePath() + "/" + type + "/" + name + ".cache"; } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/cache/file/OfflineDocumentManager.java ================================================ package moe.feng.nhentai.cache.file; import android.content.Context; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import moe.feng.nhentai.cache.common.Constants; public class OfflineDocumentManager { private FileCacheManager mCacheManager; private static OfflineDocumentManager sInstance; public static OfflineDocumentManager getInstance(Context context) { if (sInstance == null) { sInstance = new OfflineDocumentManager(context); } return sInstance; } private OfflineDocumentManager(Context context) { mCacheManager = FileCacheManager.getInstance(context); } public String getOfflineDocument(String url) { if (mCacheManager.cacheExistsUrl(Constants.CACHE_DOCUMENT, url)) { BufferedReader bf = new BufferedReader( new InputStreamReader(mCacheManager.openCacheStreamUrl(Constants.CACHE_DOCUMENT, url)) ); StringBuffer buffer = new StringBuffer(); String line = ""; try { while ((line = bf.readLine()) != null){ buffer.append(line); } } catch (IOException e) { e.printStackTrace(); } return buffer.toString(); } else { return null; } } public boolean hasOfflineCache(String url) { return mCacheManager.cacheExistsUrl(Constants.CACHE_DOCUMENT, url); } public boolean createOfflineCache(String url) { return mCacheManager.createCacheFromNetwork(Constants.CACHE_DOCUMENT, url); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/dao/CommonPreferences.java ================================================ package moe.feng.nhentai.dao; import android.content.Context; import java.util.ArrayList; import sumimakito.android.quickkv.QuickKV; import sumimakito.android.quickkv.database.KeyValueDatabase; public class CommonPreferences { private QuickKV mQuickKV; private KeyValueDatabase mKVDB; private String mDBName; private static ArrayList sInstances = new ArrayList<>(); public static CommonPreferences getInstance(Context context, String dbName) { CommonPreferences sInstance = null; for (Instance i : sInstances) { if (i.dbName == dbName) { sInstance = i.preferences; break; } } if (sInstance == null) { sInstance = new CommonPreferences(context, dbName); sInstances.add(new Instance(sInstance, dbName)); } return sInstance; } private CommonPreferences(Context context, String dbName) { this.mQuickKV = new QuickKV(context); this.mDBName = dbName; reload(); } public void sync() { this.mKVDB.sync(true); } public void reload() { this.mKVDB = this.mQuickKV.getDatabase("prefs_" + mDBName); } public Editor edit() { return new Editor(mKVDB); } public int getInt(String key, int defValue) { return contains(key) ? (int) mKVDB.get(key) : defValue; } public String getString(String key, String defValue) { return contains(key) ? (String) mKVDB.get(key) : defValue; } public boolean getBoolean(String key, boolean defValue) { return contains(key) ? (boolean) mKVDB.get(key) : defValue; } public long getLong(String key, long defValue) { return contains(key) ? (long) mKVDB.get(key) : defValue; } public float getFloat(String key, float defValue) { return contains(key) ? (float) mKVDB.get(key) : defValue; } public boolean contains(String key) { return mKVDB.containsKey(key); } public class Editor { private KeyValueDatabase mKVDB; private Editor(KeyValueDatabase kvdb) { this.mKVDB = kvdb; } public Editor putBoolean(String key, boolean value) { this.mKVDB.put(key, value); return this; } public Editor putInt(String key, int value) { this.mKVDB.put(key, value); return this; } public Editor putString(String key, String value) { this.mKVDB.put(key, value); return this; } public Editor putLong(String key, long value) { this.mKVDB.put(key, value); return this; } public Editor putFloat(String key, float value) { this.mKVDB.put(key, value); return this; } public Editor remove(String key){ this.mKVDB.remove(key); return this; } public void clear() { this.mKVDB.clear(); this.mKVDB.persist(); } public boolean commit() { return this.mKVDB.persist(); } } private static class Instance { CommonPreferences preferences; String dbName; public Instance(CommonPreferences preferences, String dbName) { this.preferences = preferences; this.dbName = dbName; } } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/dao/SearchHistoryManager.java ================================================ package moe.feng.nhentai.dao; import android.content.Context; import com.quinny898.library.persistentsearch.SearchResult; import java.util.ArrayList; import moe.feng.nhentai.R; import sumimakito.android.quickkv.QuickKV; import sumimakito.android.quickkv.database.KeyValueDatabase; public class SearchHistoryManager { private QuickKV mQuickKV; private KeyValueDatabase mDB; private String mSectionName; private static ArrayList sInstances = new ArrayList<>(); private static final String DATABASE_NAME = "search_history"; public static SearchHistoryManager getInstance(Context context, String sectionName) { SearchHistoryManager sInstance = null; for (Instance i : sInstances) { if (i.sectionName == sectionName) { sInstance = i.manager; break; } } if (sInstance == null) { sInstance = new SearchHistoryManager(context, sectionName); sInstances.add(new Instance(sInstance, sectionName)); } return sInstance; } public SearchHistoryManager(Context context, String sectionName) { this.mQuickKV = new QuickKV(context); this.mSectionName = sectionName; reloadDatabase(); } public void reloadDatabase() { mDB = mQuickKV.getDatabase(DATABASE_NAME + "_" + mSectionName); } public void add(String keyword) { int pos = find(keyword); if (pos < 0) { pos = 9; } moveArrayToNext(pos - 1); mDB.put("history_0", keyword); mDB.persist(); } public String get(int pos) { return (String) mDB.get("history_" + pos); } public int find(String keyword) { for (int i = 9; i >= 0; i--) { if (mDB.containsKey("history_" + i)) { if (mDB.get("history_" + i).equals(keyword)){ return i; } } } return -1; } private void moveArrayToNext(int end) { for (int i = end; i >= 0; i--) { if (mDB.containsKey("history_" + i)) { mDB.put("history_" + (i + 1), mDB.get("history_" + i)); } } } public void cleanAll() { mDB.clear(); mDB.persist(); } public String[] getAll() { String[] histories = new String[10]; for (int i = 0; i < 10; i++) { histories[i] = (String) mDB.get("history_" + i); } return histories; } public ArrayList getSearchResults() { ArrayList results = new ArrayList<>(); for (String history : getAll()) { if (history == null) continue; results.add(new SearchResult(history, R.drawable.ic_history)); } return results; } private static class Instance { SearchHistoryManager manager; String sectionName; public Instance(SearchHistoryManager manager, String sectionName) { this.manager = manager; this.sectionName = sectionName; } } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/model/BaseMessage.java ================================================ package moe.feng.nhentai.model; public class BaseMessage { private int code = -1; private Object data; public BaseMessage(int code, Object data) { this.code = code; this.data = data; } public BaseMessage() { } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public T getData() { return (T) data; } public void setData(Object data) { this.data = data; } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/model/Book.java ================================================ package moe.feng.nhentai.model; import com.google.gson.Gson; import java.util.ArrayList; public class Book { /** 必须获取到的数据 */ public String title, other, bookId; /** 次要数据 */ public String previewImageUrl, bigCoverImageUrl, titleJP, galleryId; public int pageCount; public int thumbHeight = 0, thumbWidth = 0; public String parodies, language, artist, group; public ArrayList tags = new ArrayList<>(); public ArrayList characters = new ArrayList<>(); public String uploadTime, uploadTimeText; public Book() { this(null, null, null); } public Book(String title, String other, String bookId) { this.title = title; this.other = other; this.bookId = bookId; } public Book(String title, String other, String bookId, String previewImageUrl) { this.title = title; this.other = other; this.bookId = bookId; this.previewImageUrl = previewImageUrl; } public String toJSONString() { return new Gson().toJson(this); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/BookDetailsActivity.java ================================================ package moe.feng.nhentai.ui; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.view.ViewCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.ContextThemeWrapper; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.github.florent37.materialimageloading.MaterialImageLoading; import com.google.gson.Gson; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import java.io.File; import moe.feng.nhentai.R; import moe.feng.nhentai.api.BookApi; import moe.feng.nhentai.api.common.NHentaiUrl; import moe.feng.nhentai.cache.common.Constants; import moe.feng.nhentai.cache.file.FileCacheManager; import moe.feng.nhentai.model.BaseMessage; import moe.feng.nhentai.model.Book; import moe.feng.nhentai.util.AsyncTask; import moe.feng.nhentai.util.ColorGenerator; import moe.feng.nhentai.util.TextDrawable; import moe.feng.nhentai.view.AutoWrapLayout; import moe.feng.nhentai.view.WheelProgressView; public class BookDetailsActivity extends AppCompatActivity { private ImageView mImageView; private CollapsingToolbarLayout collapsingToolbar; private FloatingActionButton mFAB; private TextView mTitleText; private LinearLayout mTagsLayout; private LinearLayout mContentView; private WheelProgressView mProgressWheel; private Book book; private final static String EXTRA_BOOK_DATA = "book_data"; private final static String TRANSITION_NAME_IMAGE = "BookDetailsActivity:image"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_book_details); Intent intent = getIntent(); book = new Gson().fromJson(intent.getStringExtra(EXTRA_BOOK_DATA), Book.class); Toolbar toolbar = $(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); collapsingToolbar = $(R.id.collapsing_toolbar); collapsingToolbar.setTitle(book.title); mImageView = $(R.id.app_bar_background); ViewCompat.setTransitionName(mImageView, TRANSITION_NAME_IMAGE); mFAB = $(R.id.fab); mTitleText = $(R.id.tv_title); mTagsLayout = $(R.id.book_tags_layout); mContentView = $(R.id.book_content); mProgressWheel = $(R.id.wheel_progress); FileCacheManager cm = FileCacheManager.getInstance(getApplicationContext()); if (cm.cacheExistsUrl(Constants.CACHE_THUMB, book.previewImageUrl)) { Picasso.with(getApplicationContext()) .load(cm.getBitmapUrlFile(Constants.CACHE_THUMB, book.previewImageUrl)) .fit() .centerCrop() .into(mImageView, new Callback() { @Override public void onSuccess() { MaterialImageLoading.animate(mImageView).setDuration(1500).start(); } @Override public void onError() { } }); } else { int color = ColorGenerator.MATERIAL.getColor(book.title); TextDrawable drawable = TextDrawable.builder().buildRect(book.title.substring(0, 1), color); mImageView.setImageDrawable(drawable); } if (cm.cacheExistsUrl(Constants.CACHE_COVER, book.bigCoverImageUrl)) { Picasso.with(getApplicationContext()) .load(cm.getBitmapUrlFile(Constants.CACHE_COVER, book.bigCoverImageUrl)) .fit() .centerCrop() .into(mImageView, new Callback() { @Override public void onSuccess() { MaterialImageLoading.animate(mImageView).setDuration(1500).start(); } @Override public void onError() { } }); } else { new CoverTask().execute(book); } startBookGet(); } public static void launch(Activity activity, ImageView imageView, Book book) { ActivityOptionsCompat options = ActivityOptionsCompat .makeSceneTransitionAnimation(activity, imageView, TRANSITION_NAME_IMAGE); Intent intent = new Intent(activity, BookDetailsActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); intent.putExtra(EXTRA_BOOK_DATA, book.toJSONString()); ActivityCompat.startActivity(activity, intent, options.toBundle()); } private void updateUIContent() { collapsingToolbar.setTitle(book.title); collapsingToolbar.invalidate(); $(R.id.toolbar).invalidate(); $(R.id.appbar).invalidate(); mFAB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { GalleryActivity.launch(BookDetailsActivity.this, book, 0); } }); updateDetailsContent(); } private void updateDetailsContent() { mProgressWheel.setVisibility(View.GONE); mContentView.setVisibility(View.VISIBLE); mContentView.animate().alphaBy(0f).alpha(1f).setDuration(1500).start(); mTitleText.setText(TextUtils.isEmpty(book.titleJP) ? book.title : book.titleJP); updateTagsContent(); } private void updateTagsContent() { int x = getResources().getDimensionPixelSize(R.dimen.tag_margin_x); int y = getResources().getDimensionPixelSize(R.dimen.tag_margin_y); int min_width = getResources().getDimensionPixelSize(R.dimen.tag_title_width); ContextThemeWrapper ctw = new ContextThemeWrapper(this, R.style.TextTag); // Add Parodies Tags if (!TextUtils.isEmpty(book.parodies)) { LinearLayout tagGroupLayout = new LinearLayout(this); tagGroupLayout.setOrientation(LinearLayout.HORIZONTAL); AutoWrapLayout tagLayout = new AutoWrapLayout(this); TextView groupNameView = new TextView(this); groupNameView.setMinWidth(min_width); groupNameView.setText(R.string.tag_type_parodies); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(x, y, x, y); lp.width = min_width; tagGroupLayout.addView(groupNameView, lp); TextView tagView = new TextView(ctw); tagView.setText(book.parodies); tagView.setBackgroundResource(R.color.deep_purple_800); tagView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CategoryActivity.launch( BookDetailsActivity.this, NHentaiUrl.getParodyUrl(book.parodies), getString(R.string.tag_type_parodies).trim() + " " + book.parodies ); } }); AutoWrapLayout.LayoutParams alp = new AutoWrapLayout.LayoutParams(); alp.setMargins(x, y, x, y); tagLayout.addView(tagView, alp); tagGroupLayout.addView(tagLayout); mTagsLayout.addView(tagGroupLayout); } // Add Characters if (!book.characters.isEmpty()) { LinearLayout tagGroupLayout = new LinearLayout(this); tagGroupLayout.setOrientation(LinearLayout.HORIZONTAL); AutoWrapLayout tagLayout = new AutoWrapLayout(this); TextView groupNameView = new TextView(this); groupNameView.setMinWidth(min_width); groupNameView.setText(R.string.tag_type_characters); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(x, y, x, y); lp.width = min_width; tagGroupLayout.addView(groupNameView, lp); for (final String tag : book.characters) { TextView tagView = new TextView(ctw); tagView.setText(tag); tagView.setBackgroundResource(R.color.deep_purple_800); tagView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CategoryActivity.launch( BookDetailsActivity.this, NHentaiUrl.getCharacterUrl(tag), getString(R.string.tag_type_characters).trim() + " " + tag ); } }); AutoWrapLayout.LayoutParams alp = new AutoWrapLayout.LayoutParams(); alp.setMargins(x, y, x, y); tagLayout.addView(tagView, alp); } tagGroupLayout.addView(tagLayout); mTagsLayout.addView(tagGroupLayout); } // Add Tags if (!book.tags.isEmpty()) { LinearLayout tagGroupLayout = new LinearLayout(this); tagGroupLayout.setOrientation(LinearLayout.HORIZONTAL); AutoWrapLayout tagLayout = new AutoWrapLayout(this); TextView groupNameView = new TextView(this); groupNameView.setMinWidth(min_width); groupNameView.setText(R.string.tag_type_tag); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(x, y, x, y); lp.width = min_width; tagGroupLayout.addView(groupNameView, lp); for (final String tag : book.tags) { TextView tagView = new TextView(ctw); tagView.setText(tag); tagView.setBackgroundResource(R.color.deep_purple_800); tagView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CategoryActivity.launch( BookDetailsActivity.this, NHentaiUrl.getTagUrl(tag), getString(R.string.tag_type_tag).trim() + " " + tag ); } }); AutoWrapLayout.LayoutParams alp1 = new AutoWrapLayout.LayoutParams(); alp1.setMargins(x, y, x, y); tagLayout.addView(tagView, alp1); } tagGroupLayout.addView(tagLayout); mTagsLayout.addView(tagGroupLayout); } // Add Artist Tag if (!TextUtils.isEmpty(book.artist)) { LinearLayout tagGroupLayout = new LinearLayout(this); tagGroupLayout.setOrientation(LinearLayout.HORIZONTAL); AutoWrapLayout tagLayout = new AutoWrapLayout(this); TextView groupNameView = new TextView(this); groupNameView.setMinWidth(min_width); groupNameView.setText(R.string.tag_type_artists); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(x, y, x, y); lp.width = min_width; tagGroupLayout.addView(groupNameView, lp); TextView tagView = new TextView(ctw); tagView.setText(book.artist); tagView.setBackgroundResource(R.color.deep_purple_800); tagView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CategoryActivity.launch( BookDetailsActivity.this, NHentaiUrl.getArtistUrl(book.artist), getString(R.string.tag_type_artists).trim() + " " + book.artist ); } }); AutoWrapLayout.LayoutParams alp = new AutoWrapLayout.LayoutParams(); alp.setMargins(x, y, x, y); tagLayout.addView(tagView, alp); tagGroupLayout.addView(tagLayout); mTagsLayout.addView(tagGroupLayout); } // Add Groups Tag if (!TextUtils.isEmpty(book.group)) { LinearLayout tagGroupLayout = new LinearLayout(this); tagGroupLayout.setOrientation(LinearLayout.HORIZONTAL); AutoWrapLayout tagLayout = new AutoWrapLayout(this); TextView groupNameView = new TextView(this); groupNameView.setMinWidth(min_width); groupNameView.setText(R.string.tag_type_group); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(x, y, x, y); lp.width = min_width; tagGroupLayout.addView(groupNameView, lp); TextView tagView = new TextView(ctw); tagView.setText(book.group); tagView.setBackgroundResource(R.color.deep_purple_800); tagView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CategoryActivity.launch( BookDetailsActivity.this, NHentaiUrl.getGroupUrl(book.group), getString(R.string.tag_type_group).trim() + " " + book.group ); } }); AutoWrapLayout.LayoutParams alp = new AutoWrapLayout.LayoutParams(); alp.setMargins(x, y, x, y); tagLayout.addView(tagView, alp); tagGroupLayout.addView(tagLayout); mTagsLayout.addView(tagGroupLayout); } // Add Language Tag if (!TextUtils.isEmpty(book.language)) { LinearLayout tagGroupLayout = new LinearLayout(this); tagGroupLayout.setOrientation(LinearLayout.HORIZONTAL); AutoWrapLayout tagLayout = new AutoWrapLayout(this); TextView groupNameView = new TextView(this); groupNameView.setText(R.string.tag_type_language); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(x, y, x, y); lp.width = min_width; tagGroupLayout.addView(groupNameView, lp); TextView tagView = new TextView(ctw); tagView.setText(book.language); tagView.setBackgroundResource(R.color.deep_purple_800); tagView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CategoryActivity.launch( BookDetailsActivity.this, NHentaiUrl.getLanguageUrl(book.language), getString(R.string.tag_type_language).trim() + " " + book.language ); } }); AutoWrapLayout.LayoutParams alp = new AutoWrapLayout.LayoutParams(); alp.setMargins(x, y, x, y); tagLayout.addView(tagView, alp); tagGroupLayout.addView(tagLayout); mTagsLayout.addView(tagGroupLayout); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { this.onBackPressed(); return true; } return super.onOptionsItemSelected(item); } private void startBookGet() { mContentView.setVisibility(View.GONE); mProgressWheel.setVisibility(View.VISIBLE); mProgressWheel.spin(); new BookGetTask().execute(book.bookId); } private class BookGetTask extends AsyncTask { @Override protected BaseMessage doInBackground(String... params) { return BookApi.getBook(params[0]); } @Override protected void onPostExecute(BaseMessage result) { if (result.getCode() == 0) { book = result.getData(); updateUIContent(); } else { mProgressWheel.setVisibility(View.GONE); Snackbar.make( $(R.id.main_content), R.string.tips_network_error, Snackbar.LENGTH_LONG ).setAction( R.string.snack_action_try_again, new View.OnClickListener() { @Override public void onClick(View view) { startBookGet(); } }).show(); } } } private class CoverTask extends AsyncTask { @Override protected File doInBackground(Book... params) { return BookApi.getCoverFile(BookDetailsActivity.this, params[0]); } @Override protected void onPostExecute(File result) { Picasso.with(getApplicationContext()) .load(result) .into(mImageView, new Callback() { @Override public void onSuccess() { MaterialImageLoading.animate(mImageView).setDuration(1500).start(); } @Override public void onError() { } }); } } protected T $(int id) { return (T) findViewById(id); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/CategoryActivity.java ================================================ package moe.feng.nhentai.ui; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import java.util.ArrayList; import moe.feng.nhentai.R; import moe.feng.nhentai.api.PageApi; import moe.feng.nhentai.model.BaseMessage; import moe.feng.nhentai.model.Book; import moe.feng.nhentai.ui.adapter.BookListRecyclerAdapter; import moe.feng.nhentai.ui.common.AbsActivity; import moe.feng.nhentai.ui.common.AbsRecyclerViewAdapter; import moe.feng.nhentai.util.AsyncTask; public class CategoryActivity extends AbsActivity { private RecyclerView mRecyclerView; private BookListRecyclerAdapter mAdapter; private StaggeredGridLayoutManager mLayoutManager; private SwipeRefreshLayout mSwipeRefreshLayout; private ArrayList mBooks; private int mNowPage = 1; private String url, title; private static final String EXTRA_URL = "url", EXTRA_TITLE = "title"; public static final String TAG = CategoryActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); url = intent.getStringExtra(EXTRA_URL); title = intent.getStringExtra(EXTRA_TITLE); setContentView(R.layout.activity_search_result); mActionBar.setDisplayHomeAsUpEnabled(true); mActionBar.setTitle(title); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mActionBar.setElevation(getResources().getDimension(R.dimen.appbar_elevation)); } mSwipeRefreshLayout.setRefreshing(true); new PageGetTask().execute(mNowPage); } @Override protected void setUpViews() { mRecyclerView = $(R.id.recycler_view); mSwipeRefreshLayout = $(R.id.swipe_refresh_layout); mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setHasFixedSize(true); mBooks = new ArrayList<>(); mAdapter = new BookListRecyclerAdapter(mRecyclerView, mBooks); setRecyclerViewAdapter(mAdapter); mSwipeRefreshLayout.setColorSchemeResources( R.color.deep_purple_500, R.color.pink_500, R.color.orange_500, R.color.brown_500, R.color.indigo_500, R.color.blue_500, R.color.teal_500, R.color.green_500 ); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if (!mSwipeRefreshLayout.isRefreshing()) { mSwipeRefreshLayout.setRefreshing(true); } mBooks = new ArrayList<>(); mAdapter = new BookListRecyclerAdapter(mRecyclerView, mBooks); setRecyclerViewAdapter(mAdapter); new PageGetTask().execute(mNowPage = 1); } }); } private void setRecyclerViewAdapter(BookListRecyclerAdapter adapter) { adapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() { @Override public void onItemClick(int position, AbsRecyclerViewAdapter.ClickableViewHolder viewHolder) { BookListRecyclerAdapter.ViewHolder holder = (BookListRecyclerAdapter.ViewHolder) viewHolder; BookDetailsActivity.launch(CategoryActivity.this, holder.mPreviewImageView, holder.book); } }); adapter.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView rv, int dx, int dy) { if (!mSwipeRefreshLayout.isRefreshing() && mLayoutManager.findLastCompletelyVisibleItemPositions(new int[2])[1] >= mAdapter.getItemCount() - 2) { mSwipeRefreshLayout.setRefreshing(true); new PageGetTask().execute(++mNowPage); } } }); mRecyclerView.setAdapter(adapter); } private class PageGetTask extends AsyncTask { @Override protected BaseMessage doInBackground(Integer... params) { return PageApi.getPageList(url + "/?page=" + mNowPage); } @Override protected void onPostExecute(BaseMessage msg) { mSwipeRefreshLayout.setRefreshing(false); if (msg != null) { if (msg.getCode() == 0 && msg.getData() != null) { if (!((ArrayList) msg.getData()).isEmpty()) { mBooks.addAll((ArrayList) msg.getData()); mAdapter.notifyDataSetChanged(); if (mNowPage == 1) { mRecyclerView.setAdapter(mAdapter); } } else { Snackbar.make(mRecyclerView, R.string.tips_no_result, Snackbar.LENGTH_LONG).show(); } } else if (mNowPage == 1) { Snackbar.make(mRecyclerView, R.string.tips_no_result, Snackbar.LENGTH_LONG).show(); } } } } public static void launch(AppCompatActivity activity, String url, String title) { Intent intent = new Intent(activity, CategoryActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(EXTRA_URL, url); intent.putExtra(EXTRA_TITLE, title); activity.startActivity(intent); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/GalleryActivity.java ================================================ package moe.feng.nhentai.ui; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.View; import android.view.WindowManager; import com.google.gson.Gson; import moe.feng.nhentai.R; import moe.feng.nhentai.model.Book; import moe.feng.nhentai.ui.adapter.GalleryPagerAdapter; import moe.feng.nhentai.ui.common.AbsActivity; import moe.feng.nhentai.util.FullScreenHelper; public class GalleryActivity extends AbsActivity { private Book book; private int page_num; private ViewPager mPager; private GalleryPagerAdapter mPagerAdpater; private View mAppBar; private FullScreenHelper mFullScreenHelper; private static final String EXTRA_BOOK_DATA = "book_data", EXTRA_FISRT_PAGE = "first_page"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= 21) { getWindow().setStatusBarColor(Color.TRANSPARENT); getWindow().setNavigationBarColor(Color.TRANSPARENT); } mFullScreenHelper = new FullScreenHelper(this); // 别问我为什么这么干 让我先冷静一下→_→ mFullScreenHelper.setFullScreen(true); mFullScreenHelper.setFullScreen(false); Intent intent = getIntent(); book = new Gson().fromJson(intent.getStringExtra(EXTRA_BOOK_DATA), Book.class); page_num = intent.getIntExtra(EXTRA_FISRT_PAGE, 0); setContentView(R.layout.activity_gallery); } @Override protected void setUpViews() { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(book.titleJP != null ? book.titleJP : book.title); mAppBar = $(R.id.my_app_bar); mPager = $(R.id.pager); mPagerAdpater = new GalleryPagerAdapter(getFragmentManager(), book); mPager.setAdapter(mPagerAdpater); mPager.setCurrentItem(page_num, false); } public static void launch(Activity activity, Book book, int firstPageNum) { Intent intent = new Intent(activity, GalleryActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); intent.putExtra(EXTRA_BOOK_DATA, book.toJSONString()); intent.putExtra(EXTRA_FISRT_PAGE, firstPageNum); activity.startActivity(intent); } public void toggleControlBar() { if (mAppBar.getAlpha() != 0f) { mAppBar.animate().alpha(0f).start(); mFullScreenHelper.setFullScreen(true); } else if (mAppBar.getAlpha() != 1f) { mAppBar.animate().alpha(1f).start(); mFullScreenHelper.setFullScreen(false); } } @Override public void onBackPressed() { if (mAppBar.getAlpha() != 1f) { toggleControlBar(); } else { super.onBackPressed(); } } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/MainActivity.java ================================================ package moe.feng.nhentai.ui; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.quinny898.library.persistentsearch.SearchBox; import moe.feng.nhentai.R; import moe.feng.nhentai.dao.SearchHistoryManager; import moe.feng.nhentai.ui.adapter.HomePagerAdapter; import moe.feng.nhentai.ui.common.AbsActivity; public class MainActivity extends AbsActivity implements NavigationView.OnNavigationItemSelectedListener { private ViewPager mPager; private HomePagerAdapter mPagerAdapter; private TabLayout mTabLayout; private SearchBox mSearchBox; private DrawerLayout mDrawerLayout; private NavigationView mNavigationView; private ActionBarDrawerToggle mDrawerToggle; private SearchHistoryManager mSearchHistoryManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState, false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(getResources().getColor(R.color.deep_purple_800)); } setContentView(R.layout.activity_main); mActionBar.setDisplayHomeAsUpEnabled(true); mSearchHistoryManager = SearchHistoryManager.getInstance(getApplicationContext(), "all"); } @Override protected void setUpViews() { mPager = $(R.id.viewpager); mTabLayout = $(R.id.tabs); mSearchBox = $(R.id.search_box); mDrawerLayout = $(R.id.drawer_layout); mNavigationView = $(R.id.navigation_view); mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() { @Override public void onDrawerOpened(View drawerView) { mDrawerToggle.onDrawerOpened(drawerView); } @Override public void onDrawerClosed(View drawerView) { mDrawerToggle.onDrawerClosed(drawerView); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { mDrawerToggle.onDrawerSlide(drawerView, slideOffset); } @Override public void onDrawerStateChanged(int newState) { mDrawerToggle.onDrawerStateChanged(newState); } }); mNavigationView.setNavigationItemSelectedListener(this); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.abc_action_bar_home_description, R.string.abc_action_bar_home_description ) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); invalidateOptionsMenu(); } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); invalidateOptionsMenu(); } }; mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); mPagerAdapter = new HomePagerAdapter(getApplicationContext(), getFragmentManager()); mPager.setAdapter(mPagerAdapter); mTabLayout.setupWithViewPager(mPager); mSearchBox.setLogoText(""); mSearchBox.setSearchListener(new SearchBox.SearchListener() { @Override public void onSearchOpened() { } @Override public void onSearchCleared() { } @Override public void onSearchClosed() { closeSearchBox(); } @Override public void onSearchTermChanged() { } @Override public void onSearch(String result) { mSearchHistoryManager.add(result); SearchResultActivity.launch(MainActivity.this, result); } }); } private void openSearchBox() { mSearchBox.setVisibility(View.VISIBLE); mSearchBox.setSearchables(mSearchHistoryManager.getSearchResults()); mSearchBox.setSearchString(""); mSearchBox.revealFromMenuItem(R.id.action_search, this); } private void closeSearchBox() { mSearchBox.hideCircularly(this); new Handler().postDelayed(new Runnable() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { mSearchBox.setVisibility(View.INVISIBLE); } }); } }, 250); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } int id = item.getItemId(); if (id == R.id.action_search) { openSearchBox(); return true; } if (id == R.id.action_settings) { SettingsActivity.launchActivity(this, SettingsActivity.FLAG_MAIN); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (mSearchBox.isSearchOpened()) { mSearchBox.toggleSearch(); } else { super.onBackPressed(); } } @Override public boolean onNavigationItemSelected(MenuItem menuItem) { mDrawerLayout.closeDrawer(mNavigationView); switch (menuItem.getItemId()) { // TODO Update page case R.id.navigation_item_home: menuItem.setChecked(true); return true; case R.id.navigation_item_tag: return true; case R.id.navigation_item_character: return true; } return false; } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/SearchResultActivity.java ================================================ package moe.feng.nhentai.ui; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import java.util.ArrayList; import moe.feng.nhentai.R; import moe.feng.nhentai.api.PageApi; import moe.feng.nhentai.model.BaseMessage; import moe.feng.nhentai.model.Book; import moe.feng.nhentai.ui.adapter.BookListRecyclerAdapter; import moe.feng.nhentai.ui.common.AbsActivity; import moe.feng.nhentai.ui.common.AbsRecyclerViewAdapter; import moe.feng.nhentai.util.AsyncTask; public class SearchResultActivity extends AbsActivity { private RecyclerView mRecyclerView; private BookListRecyclerAdapter mAdapter; private StaggeredGridLayoutManager mLayoutManager; private SwipeRefreshLayout mSwipeRefreshLayout; private ArrayList mBooks; private int mNowPage = 1; private String keyword; private static final String EXTRA_KEYWORD = "keyword"; public static final String TAG = SearchResultActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); keyword = intent.getStringExtra(EXTRA_KEYWORD); setContentView(R.layout.activity_search_result); mActionBar.setDisplayHomeAsUpEnabled(true); mActionBar.setTitle(String.format(getString(R.string.title_search_result), keyword)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mActionBar.setElevation(getResources().getDimension(R.dimen.appbar_elevation)); } mSwipeRefreshLayout.setRefreshing(true); new PageGetTask().execute(mNowPage); } @Override protected void setUpViews() { mRecyclerView = $(R.id.recycler_view); mSwipeRefreshLayout = $(R.id.swipe_refresh_layout); mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setHasFixedSize(true); mBooks = new ArrayList<>(); mAdapter = new BookListRecyclerAdapter(mRecyclerView, mBooks); setRecyclerViewAdapter(mAdapter); mSwipeRefreshLayout.setColorSchemeResources( R.color.deep_purple_500, R.color.pink_500, R.color.orange_500, R.color.brown_500, R.color.indigo_500, R.color.blue_500, R.color.teal_500, R.color.green_500 ); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if (!mSwipeRefreshLayout.isRefreshing()) { mSwipeRefreshLayout.setRefreshing(true); } mBooks = new ArrayList<>(); mAdapter = new BookListRecyclerAdapter(mRecyclerView, mBooks); setRecyclerViewAdapter(mAdapter); new PageGetTask().execute(mNowPage = 1); } }); } private void setRecyclerViewAdapter(BookListRecyclerAdapter adapter) { adapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() { @Override public void onItemClick(int position, AbsRecyclerViewAdapter.ClickableViewHolder viewHolder) { BookListRecyclerAdapter.ViewHolder holder = (BookListRecyclerAdapter.ViewHolder) viewHolder; BookDetailsActivity.launch(SearchResultActivity.this, holder.mPreviewImageView, holder.book); } }); adapter.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView rv, int dx, int dy) { if (!mSwipeRefreshLayout.isRefreshing() && mLayoutManager.findLastCompletelyVisibleItemPositions(new int[2])[1] >= mAdapter.getItemCount() - 2) { mSwipeRefreshLayout.setRefreshing(true); new PageGetTask().execute(++mNowPage); } } }); mRecyclerView.setAdapter(adapter); } private class PageGetTask extends AsyncTask { @Override protected BaseMessage doInBackground(Integer... params) { return PageApi.getSearchPageList(keyword, params[0]); } @Override protected void onPostExecute(BaseMessage msg) { mSwipeRefreshLayout.setRefreshing(false); if (msg != null) { if (msg.getCode() == 0 && msg.getData() != null) { if (!((ArrayList) msg.getData()).isEmpty()) { mBooks.addAll((ArrayList) msg.getData()); mAdapter.notifyDataSetChanged(); if (mNowPage == 1) { mRecyclerView.setAdapter(mAdapter); } } else { Snackbar.make(mRecyclerView, R.string.tips_no_result, Snackbar.LENGTH_LONG).show(); } } else if (mNowPage == 1) { Snackbar.make(mRecyclerView, R.string.tips_no_result, Snackbar.LENGTH_LONG).show(); } } } } public static void launch(AppCompatActivity activity, String keyword) { Intent intent = new Intent(activity, SearchResultActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(EXTRA_KEYWORD, keyword); activity.startActivity(intent); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/SettingsActivity.java ================================================ package moe.feng.nhentai.ui; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewCompat; import moe.feng.nhentai.R; import moe.feng.nhentai.ui.common.AbsActivity; import moe.feng.nhentai.ui.fragment.settings.SettingsLicense; import moe.feng.nhentai.ui.fragment.settings.SettingsMain; public class SettingsActivity extends AbsActivity { private Fragment mFragment; private int flag; public static final String EXTRA_FLAG = "flag"; public static final int FLAG_MAIN = 0, FLAG_LICENSE = 1, FLAG_GUI = 2, FLAG_NETWORK = 3; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); flag = intent.getIntExtra(EXTRA_FLAG, FLAG_MAIN); setContentView(R.layout.activity_settings); mActionBar.setDisplayHomeAsUpEnabled(true); } @Override public void setUpViews() { ViewCompat.setElevation(mToolbar, getResources().getDimension(R.dimen.appbar_elevation)); switch (flag) { case FLAG_MAIN: mFragment = new SettingsMain(); break; case FLAG_LICENSE: mFragment = new SettingsLicense(); break; } getFragmentManager().beginTransaction() .replace(R.id.container, mFragment) .commit(); } public static void launchActivity(Activity mActivity, int flag) { Intent intent = new Intent(mActivity, SettingsActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); intent.putExtra(EXTRA_FLAG, flag); mActivity.startActivity(intent); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/adapter/BookListRecyclerAdapter.java ================================================ package moe.feng.nhentai.ui.adapter; import android.graphics.Bitmap; import android.support.v7.widget.ListPopupWindow; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import moe.feng.nhentai.R; import moe.feng.nhentai.api.BookApi; import moe.feng.nhentai.model.Book; import moe.feng.nhentai.ui.common.AbsRecyclerViewAdapter; import moe.feng.nhentai.util.AsyncTask; import moe.feng.nhentai.util.ColorGenerator; import moe.feng.nhentai.util.TextDrawable; import moe.feng.nhentai.util.Utility; public class BookListRecyclerAdapter extends AbsRecyclerViewAdapter { private ArrayList data; private ColorGenerator mColorGenerator; public static final String TAG = BookListRecyclerAdapter.class.getSimpleName(); public BookListRecyclerAdapter(RecyclerView recyclerView, ArrayList data) { super(recyclerView); this.data = data; mColorGenerator = ColorGenerator.MATERIAL; } @Override public ClickableViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { bindContext(viewGroup.getContext()); View view = LayoutInflater.from(getContext()).inflate(R.layout.list_item_book_card, viewGroup, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ClickableViewHolder holder, final int position) { super.onBindViewHolder(holder, position); if (holder instanceof ViewHolder) { final ViewHolder mHolder = (ViewHolder) holder; mHolder.mTitleTextView.setText(data.get(position).title); String previewImageUrl = data.get(position).previewImageUrl; int color = mColorGenerator.getColor(data.get(position).title); TextDrawable drawable = TextDrawable.builder().buildRect(Utility.getFirstCharacter(data.get(position).title), color); mHolder.mPreviewImageView.setImageDrawable(drawable); if (previewImageUrl != null) { switch (previewImageUrl) { case "0": mHolder.mPreviewImageView.setImageResource(R.drawable.holder_0); break; case "1": mHolder.mPreviewImageView.setImageResource(R.drawable.holder_1); break; case "2": mHolder.mPreviewImageView.setImageResource(R.drawable.holder_2); break; default: ViewTreeObserver vto = mHolder.mPreviewImageView.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int thumbWidth = data.get(position).thumbWidth; int thumbHeight = data.get(position).thumbHeight; if (thumbWidth > 0 && thumbHeight > 0) { int width = mHolder.mPreviewImageView.getMeasuredWidth(); int height = Math.round(width * ((float) thumbHeight / thumbWidth)); mHolder.mPreviewImageView.getLayoutParams().height = height; mHolder.mPreviewImageView.setMinimumHeight(height); } mHolder.mPreviewImageView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } }); new ImageDownloader().execute(mHolder.getParentView()); } } mHolder.book = data.get(position); } } @Override public int getItemCount() { return data.size(); } private class ImageDownloader extends AsyncTask { @Override protected Void doInBackground(Object[] params) { View v = (View) params[0]; ViewHolder h = (ViewHolder) v.getTag(); Book book = h.book; if (v != null && !TextUtils.isEmpty(book.previewImageUrl)) { ImageView imgView = h.mPreviewImageView; Bitmap img = BookApi.getThumb(getContext(), book); if (img != null) { publishProgress(new Object[]{v, img, imgView, book}); } } return null; } @Override protected void onProgressUpdate(Object[] values) { super.onProgressUpdate(values); View v = (View) values[0]; if (!(v.getTag() instanceof ViewHolder) || (((ViewHolder) v.getTag()).book != null && ((ViewHolder) v.getTag()).book.bookId != ((Book) values[3]).bookId)) { return; } Bitmap img = (Bitmap) values[1]; ImageView iv = (ImageView) values[2]; iv.setVisibility(View.VISIBLE); iv.setImageBitmap(img); iv.setTag(false); } } public class ViewHolder extends ClickableViewHolder { public ImageView mPreviewImageView; public TextView mTitleTextView; public Book book; public ViewHolder(View itemView) { super(itemView); mPreviewImageView = (ImageView) itemView.findViewById(R.id.book_preview); mTitleTextView = (TextView) itemView.findViewById(R.id.book_title); itemView.setTag(this); } } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/adapter/BookPreviewGridAdapter.java ================================================ package moe.feng.nhentai.ui.adapter; import android.content.Context; import android.graphics.Bitmap; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import moe.feng.nhentai.R; import moe.feng.nhentai.api.BookApi; import moe.feng.nhentai.model.Book; import moe.feng.nhentai.util.AsyncTask; public class BookPreviewGridAdapter extends BaseAdapter { private Book book; private Context mContext; public BookPreviewGridAdapter(Context context, Book book) { super(); this.mContext = context; this.book = book; } @Override public int getCount() { return book.pageCount; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int position, View view, ViewGroup viewGroup) { ViewHolder holder; if (view == null) { view = View.inflate(mContext, R.layout.list_item_book_picture_thumb, null); holder = new ViewHolder(view); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } holder.mImageView.setLayoutParams(new GridView.LayoutParams(300, 100)); holder.mNumberText.setText(position); new ImageDownloader().execute(holder.mImageView, position); return view; } private class ViewHolder { View mParentView; ImageView mImageView; TextView mNumberText; public ViewHolder(View itemView) { this.mParentView = itemView; this.mImageView = (ImageView) itemView.findViewById(R.id.image_view); this.mNumberText = (TextView) itemView.findViewById(R.id.number_text); } } private class ImageDownloader extends AsyncTask { @Override protected Void doInBackground(Object[] params) { View v = (View) params[0]; ViewHolder h = (ViewHolder) v.getTag(); if (v != null && !TextUtils.isEmpty(book.previewImageUrl)) { ImageView imgView = h.mImageView; Bitmap img = BookApi.getPageThumb(mContext, book, (int) params[1]); if (img != null) { publishProgress(new Object[]{v, img, imgView, book}); } } return null; } @Override protected void onProgressUpdate(Object[] values) { super.onProgressUpdate(values); View v = (View) values[0]; if (!(v.getTag() instanceof ViewHolder)) { return; } Bitmap img = (Bitmap) values[1]; ImageView iv = (ImageView) values[2]; iv.setVisibility(View.VISIBLE); iv.setImageBitmap(img); iv.setTag(false); } } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/adapter/GalleryPagerAdapter.java ================================================ package moe.feng.nhentai.ui.adapter; import android.app.Fragment; import android.app.FragmentManager; import android.support.v13.app.FragmentPagerAdapter; import moe.feng.nhentai.model.Book; import moe.feng.nhentai.ui.fragment.BookPageFragment; public class GalleryPagerAdapter extends FragmentPagerAdapter { private Book book; private Fragment[] fragments; public GalleryPagerAdapter(FragmentManager fm, Book book) { super(fm); this.book = book; this.fragments = new Fragment[book.pageCount]; } @Override public Fragment getItem(int position) { if (fragments[position] == null) { fragments[position] = BookPageFragment.newInstance(book, position + 1); } return fragments[position]; } @Override public int getCount() { return book.pageCount; } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/adapter/HomePagerAdapter.java ================================================ package moe.feng.nhentai.ui.adapter; import android.app.Fragment; import android.app.FragmentManager; import android.content.Context; import android.support.v13.app.FragmentPagerAdapter; import moe.feng.nhentai.R; import moe.feng.nhentai.ui.fragment.main.DownloadManagerFragment; import moe.feng.nhentai.ui.fragment.main.FavoriteFragment; import moe.feng.nhentai.ui.fragment.main.HomeFragment; public class HomePagerAdapter extends FragmentPagerAdapter { private HomeFragment homeFragment; private DownloadManagerFragment downloadManagerFragment; private FavoriteFragment favoriteFragment; private String[] titles; public HomePagerAdapter(Context context, FragmentManager fm) { super(fm); titles = context.getResources().getStringArray(R.array.page_titles); homeFragment = new HomeFragment(); downloadManagerFragment = new DownloadManagerFragment(); favoriteFragment = new FavoriteFragment(); } @Override public Fragment getItem(int position) { switch (position) { case 0: return homeFragment; case 1: return downloadManagerFragment; case 2: return favoriteFragment; default: return null; } } @Override public int getCount() { return 3; } @Override public CharSequence getPageTitle(int position) { return titles[position]; } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/common/AbsActivity.java ================================================ package moe.feng.nhentai.ui.common; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import moe.feng.nhentai.R; import moe.feng.nhentai.util.Utility; public abstract class AbsActivity extends AppCompatActivity { protected Toolbar mToolbar; protected ActionBar mActionBar; protected int statusBarHeight = 0; @Override protected void onCreate(Bundle savedInstanceState) { this.onCreate(savedInstanceState, true); } protected void onCreate(Bundle savedInstanceState, boolean statusBarTranslucent) { /** Set up translucent status bar */ if (statusBarTranslucent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && !Utility.isChrome()) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); statusBarHeight = Utility.getStatusBarHeight(getApplicationContext()); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(Color.TRANSPARENT); getWindow().setNavigationBarColor(getResources().getColor(R.color.deep_purple_800)); } } super.onCreate(savedInstanceState); } protected abstract void setUpViews(); @Override public void setContentView(@LayoutRes int layoutResId) { super.setContentView(layoutResId); try { View statusHeaderView = $(R.id.status_bar_header); statusHeaderView.getLayoutParams().height = statusBarHeight; } catch (NullPointerException e) { Log.e("setContentView", "Cannot find status header."); } try { mToolbar = $(R.id.toolbar); setSupportActionBar(mToolbar); } catch (Exception e) { Log.e("setContentView", "Cannot find toolbar."); } mActionBar = getSupportActionBar(); setUpViews(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { this.onBackPressed(); return true; } return super.onOptionsItemSelected(item); } protected T $(int id) { return (T) findViewById(id); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/common/AbsRecyclerViewAdapter.java ================================================ package moe.feng.nhentai.ui.common; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.View; import java.util.ArrayList; import java.util.List; public abstract class AbsRecyclerViewAdapter extends RecyclerView.Adapter { private Context context; protected RecyclerView mRecyclerView; protected List mListeners = new ArrayList(); public AbsRecyclerViewAdapter(RecyclerView recyclerView) { this.mRecyclerView = recyclerView; this.mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView rv, int newState) { for (RecyclerView.OnScrollListener listener : mListeners) { listener.onScrollStateChanged(rv, newState); } } @Override public void onScrolled(RecyclerView rv, int dx, int dy) { for (RecyclerView.OnScrollListener listener : mListeners) { listener.onScrolled(rv, dx, dy); } } }); } public void addOnScrollListener(RecyclerView.OnScrollListener listener) { mListeners.add(listener); } public interface OnItemClickListener { public void onItemClick(int position, ClickableViewHolder holder); } public interface OnItemLongClickListener { public boolean onItemLongClick(int position, ClickableViewHolder holder); } private OnItemClickListener itemClickListener; private OnItemLongClickListener itemLongClickListener; public void setOnItemClickListener(OnItemClickListener listener) { this.itemClickListener = listener; } public void setOnItemLongClickListener(OnItemLongClickListener listener) { this.itemLongClickListener = listener; } public void bindContext(Context context) { this.context = context; } public Context getContext() { return this.context; } @Override public void onBindViewHolder(final ClickableViewHolder holder, final int position) { holder.getParentView().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (itemClickListener != null) { itemClickListener.onItemClick(position, holder); } } }); holder.getParentView().setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (itemLongClickListener != null) { return itemLongClickListener.onItemLongClick(position, holder); } else { return false; } } }); } public class ClickableViewHolder extends RecyclerView.ViewHolder { private View parentView; public ClickableViewHolder(View itemView) { super(itemView); this.parentView = itemView; } public View getParentView() { return parentView; } } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/fragment/BookPageFragment.java ================================================ package moe.feng.nhentai.ui.fragment; import android.app.Fragment; import android.graphics.Bitmap; import android.graphics.PointF; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.github.florent37.materialimageloading.MaterialImageLoading; import com.google.gson.Gson; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import java.io.File; import moe.feng.nhentai.R; import moe.feng.nhentai.api.PageApi; import moe.feng.nhentai.model.Book; import moe.feng.nhentai.ui.GalleryActivity; import moe.feng.nhentai.util.AsyncTask; import uk.co.senab.photoview.PhotoViewAttacher; public class BookPageFragment extends Fragment { private Book book; private int pageNum; private ImageView mImageView; private PhotoViewAttacher mPhotoViewAttacher; private static final String ARG_BOOK_DATA = "arg_book_data", ARG_PAGE_NUM = "arg_page_num"; public static final String TAG = BookPageFragment.class.getSimpleName(); public static BookPageFragment newInstance(Book book, int pageNum) { BookPageFragment fragment = new BookPageFragment(); Bundle data = new Bundle(); data.putString(ARG_BOOK_DATA, book.toJSONString()); data.putInt(ARG_PAGE_NUM, pageNum); fragment.setArguments(data); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle data = getArguments(); book = new Gson().fromJson(data.getString(ARG_BOOK_DATA), Book.class); pageNum = data.getInt(ARG_PAGE_NUM); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) { View view = inflater.inflate(R.layout.fragment_book_page, container, false); mImageView = (ImageView) view.findViewById(R.id.image_view); mPhotoViewAttacher = new PhotoViewAttacher(mImageView); new DownloadTask().execute(); return view; } private class DownloadTask extends AsyncTask { @Override protected File doInBackground(Void... params) { return PageApi.getPageOriginImageFile(getActivity().getApplicationContext(), book, pageNum); } @Override protected void onPostExecute(File result) { super.onPostExecute(result); if (result != null) { Picasso.with(getActivity().getApplicationContext()) .load(result) .into(mImageView, new Callback() { @Override public void onSuccess() { MaterialImageLoading.animate(mImageView).setDuration(700).start(); mPhotoViewAttacher.update(); mPhotoViewAttacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() { @Override public void onViewTap(View view, float v, float v1) { ((GalleryActivity) getActivity()).toggleControlBar(); } }); } @Override public void onError() { } }); } } } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/fragment/main/DownloadManagerFragment.java ================================================ package moe.feng.nhentai.ui.fragment.main; import android.app.Fragment; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import moe.feng.nhentai.R; import moe.feng.nhentai.model.Book; import moe.feng.nhentai.ui.BookDetailsActivity; import moe.feng.nhentai.ui.adapter.BookListRecyclerAdapter; import moe.feng.nhentai.ui.common.AbsRecyclerViewAdapter; public class DownloadManagerFragment extends Fragment { private RecyclerView mRecyclerView; private BookListRecyclerAdapter mAdapter; public static final String TAG = DownloadManagerFragment.class.getSimpleName(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) { View view = inflater.inflate(R.layout.fragment_home, container, false); mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); mRecyclerView.setHasFixedSize(false); ArrayList books = new ArrayList<>(); mAdapter = new BookListRecyclerAdapter(mRecyclerView, books); mAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() { @Override public void onItemClick(int position, AbsRecyclerViewAdapter.ClickableViewHolder viewHolder) { if (viewHolder instanceof BookListRecyclerAdapter.ViewHolder) { BookListRecyclerAdapter.ViewHolder holder = (BookListRecyclerAdapter.ViewHolder) viewHolder; Log.i(TAG, "You clicked position no." + position + " item, " + "its name is " + holder.mTitleTextView.getText().toString()); } } }); setRecyclerViewAdapter(mAdapter); return view; } private void setRecyclerViewAdapter(BookListRecyclerAdapter adapter) { mRecyclerView.setAdapter(mAdapter); mAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() { @Override public void onItemClick(int position, AbsRecyclerViewAdapter.ClickableViewHolder viewHolder) { BookListRecyclerAdapter.ViewHolder holder = (BookListRecyclerAdapter.ViewHolder) viewHolder; Log.i(TAG, "You clicked position no." + position + " item, " + "its name is " + holder.mTitleTextView.getText().toString()); BookDetailsActivity.launch(getActivity(), holder.mPreviewImageView, holder.book); } }); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/fragment/main/FavoriteFragment.java ================================================ package moe.feng.nhentai.ui.fragment.main; import android.app.Fragment; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import moe.feng.nhentai.R; import moe.feng.nhentai.model.Book; import moe.feng.nhentai.ui.BookDetailsActivity; import moe.feng.nhentai.ui.adapter.BookListRecyclerAdapter; import moe.feng.nhentai.ui.common.AbsRecyclerViewAdapter; public class FavoriteFragment extends Fragment { private RecyclerView mRecyclerView; private BookListRecyclerAdapter mAdapter; public static final String TAG = FavoriteFragment.class.getSimpleName(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) { View view = inflater.inflate(R.layout.fragment_home, container, false); mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); mRecyclerView.setHasFixedSize(false); ArrayList books = new ArrayList<>(); mAdapter = new BookListRecyclerAdapter(mRecyclerView, books); mAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() { @Override public void onItemClick(int position, AbsRecyclerViewAdapter.ClickableViewHolder viewHolder) { if (viewHolder instanceof BookListRecyclerAdapter.ViewHolder) { BookListRecyclerAdapter.ViewHolder holder = (BookListRecyclerAdapter.ViewHolder) viewHolder; Log.i(TAG, "You clicked position no." + position + " item, " + "its name is " + holder.mTitleTextView.getText().toString()); } } }); setRecyclerViewAdapter(mAdapter); return view; } private void setRecyclerViewAdapter(BookListRecyclerAdapter adapter) { mRecyclerView.setAdapter(mAdapter); mAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() { @Override public void onItemClick(int position, AbsRecyclerViewAdapter.ClickableViewHolder viewHolder) { BookListRecyclerAdapter.ViewHolder holder = (BookListRecyclerAdapter.ViewHolder) viewHolder; Log.i(TAG, "You clicked position no." + position + " item, " + "its name is " + holder.mTitleTextView.getText().toString()); BookDetailsActivity.launch(getActivity(), holder.mPreviewImageView, holder.book); } }); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/fragment/main/HomeFragment.java ================================================ package moe.feng.nhentai.ui.fragment.main; import android.app.Fragment; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import moe.feng.nhentai.R; import moe.feng.nhentai.api.PageApi; import moe.feng.nhentai.model.BaseMessage; import moe.feng.nhentai.model.Book; import moe.feng.nhentai.ui.BookDetailsActivity; import moe.feng.nhentai.ui.adapter.BookListRecyclerAdapter; import moe.feng.nhentai.ui.common.AbsRecyclerViewAdapter; import moe.feng.nhentai.util.AsyncTask; public class HomeFragment extends Fragment { private RecyclerView mRecyclerView; private BookListRecyclerAdapter mAdapter; private StaggeredGridLayoutManager mLayoutManager; private SwipeRefreshLayout mSwipeRefreshLayout; private ArrayList mBooks; private int mNowPage = 1; public static final String TAG = HomeFragment.class.getSimpleName(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) { View view = inflater.inflate(R.layout.fragment_home, container, false); mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout); mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setHasFixedSize(true); mBooks = new ArrayList<>(); mAdapter = new BookListRecyclerAdapter(mRecyclerView, mBooks); setRecyclerViewAdapter(mAdapter); mSwipeRefreshLayout.setColorSchemeResources( R.color.deep_purple_500, R.color.pink_500, R.color.orange_500, R.color.brown_500, R.color.indigo_500, R.color.blue_500, R.color.teal_500, R.color.green_500 ); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if (!mSwipeRefreshLayout.isRefreshing()) { mSwipeRefreshLayout.setRefreshing(true); } mBooks = new ArrayList<>(); mAdapter = new BookListRecyclerAdapter(mRecyclerView, mBooks); setRecyclerViewAdapter(mAdapter); new PageGetTask().execute(mNowPage = 1); } }); new PageGetTask().execute(mNowPage); return view; } private void setRecyclerViewAdapter(BookListRecyclerAdapter adapter) { adapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() { @Override public void onItemClick(int position, AbsRecyclerViewAdapter.ClickableViewHolder viewHolder) { BookListRecyclerAdapter.ViewHolder holder = (BookListRecyclerAdapter.ViewHolder) viewHolder; Log.i(TAG, "You clicked position no." + position + " item, " + "its name is " + holder.mTitleTextView.getText().toString()); BookDetailsActivity.launch(getActivity(), holder.mPreviewImageView, holder.book); } }); adapter.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView rv, int dx, int dy) { if (!mSwipeRefreshLayout.isRefreshing() && mLayoutManager.findLastCompletelyVisibleItemPositions(new int[2])[1] >= mAdapter.getItemCount() - 2) { mSwipeRefreshLayout.setRefreshing(true); new PageGetTask().execute(++mNowPage); } } }); mRecyclerView.setAdapter(adapter); } private class PageGetTask extends AsyncTask { @Override protected BaseMessage doInBackground(Integer... params) { return PageApi.getHomePageList(params[0]); } @Override protected void onPostExecute(BaseMessage msg) { mSwipeRefreshLayout.setRefreshing(false); if (msg != null) { if (msg.getCode() == 0 && msg.getData() != null) { if (!((ArrayList) msg.getData()).isEmpty()) { mBooks.addAll((ArrayList) msg.getData()); mAdapter.notifyDataSetChanged(); } } else if (mNowPage == 1) { Snackbar.make( mRecyclerView, R.string.tips_network_error, Snackbar.LENGTH_LONG ).setAction( R.string.snack_action_try_again, new View.OnClickListener() { @Override public void onClick(View view) { mSwipeRefreshLayout.setRefreshing(true); new PageGetTask().execute(mNowPage); } } ).show(); } } } } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/fragment/settings/SettingsLicense.java ================================================ package moe.feng.nhentai.ui.fragment.settings; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import moe.feng.nhentai.R; public class SettingsLicense extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle bundle) { WebView webView = new WebView(inflater.getContext()); webView.loadUrl("file:///android_asset/licenses.html"); getActivity().setTitle(R.string.settings_license); return webView; } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/ui/fragment/settings/SettingsMain.java ================================================ package moe.feng.nhentai.ui.fragment.settings; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceFragment; import moe.feng.nhentai.R; import moe.feng.nhentai.ui.SettingsActivity; import moe.feng.nhentai.view.pref.Preference; public class SettingsMain extends PreferenceFragment implements Preference.OnPreferenceClickListener { private Preference mVersionPref; private Preference mLicensePref; private Preference mWeiboPref; private Preference mGooglePlusPref; private Preference mGithubPref; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings_main); mVersionPref = (Preference) findPreference("version"); mLicensePref = (Preference) findPreference("license"); mWeiboPref = (Preference) findPreference("weibo"); mGooglePlusPref = (Preference) findPreference("google_plus"); mGithubPref = (Preference) findPreference("github"); String version = "Unknown"; try { version = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName; version += " (" + getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionCode + ")"; } catch (Exception e) { } mVersionPref.setSummary(version); mLicensePref.setOnPreferenceClickListener(this); mWeiboPref.setOnPreferenceClickListener(this); mGooglePlusPref.setOnPreferenceClickListener(this); mGithubPref.setOnPreferenceClickListener(this); } @Override public boolean onPreferenceClick(android.preference.Preference pref) { if (pref == mLicensePref) { SettingsActivity.launchActivity(getActivity(), SettingsActivity.FLAG_LICENSE); return true; } if (pref == mWeiboPref) { openWebUrl("http://weibo.com/fython"); return true; } if (pref == mGooglePlusPref) { openWebUrl("https://plus.google.com/+FungJichun"); return true; } if (pref == mGithubPref) { openWebUrl(getString(R.string.set_title_github_website)); } return false; } private void openWebUrl(String url) { Uri uri = Uri.parse(url); startActivity(new Intent(Intent.ACTION_VIEW, uri)); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/util/AsyncTask.java ================================================ package moe.feng.nhentai.util; import android.os.Handler; import android.os.Message; import android.util.Log; import static moe.feng.nhentai.BuildConfig.DEBUG; /* Real AsyncTask */ public abstract class AsyncTask { private static final String TAG = AsyncTask.class.getSimpleName(); private static class AsyncResult { public AsyncTask task; public Data[] data; public AsyncResult(AsyncTask task, Data... data) { this.task = task; this.data = data; } } private static final int MSG_FINISH = 1000; private static final int MSG_PROGRESS = 1001; private static Handler sInternalHandler = new Handler() { @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { AsyncResult result = (AsyncResult) msg.obj; switch (msg.what) { case MSG_FINISH: result.task.onPostExecute(result.data[0]); break; case MSG_PROGRESS: result.task.onProgressUpdate(result.data); break; } } }; private Params[] mParams; private Thread mThread = new Thread(new Runnable() { @Override public void run() { // TODO: CrashHandler.register(); try { Result result = doInBackground(mParams); sInternalHandler.sendMessage(sInternalHandler.obtainMessage(MSG_FINISH, new AsyncResult(AsyncTask.this, result))); } catch (Exception e) { // Don't crash the whole app if (DEBUG) { Log.d(TAG, e.getClass().getSimpleName() + " caught when running background task. Printing stack trace."); Log.d(TAG, Log.getStackTraceString(e)); } } Thread.currentThread().interrupt(); } }); protected void onPostExecute(Result result) {} protected abstract Result doInBackground(Params... params); protected void onPreExecute() {} protected void onProgressUpdate(Progress... progress) {} protected void publishProgress(Progress... progress) { sInternalHandler.sendMessage(sInternalHandler.obtainMessage(MSG_PROGRESS, new AsyncResult(this, progress))); } public void execute(Params... params) { onPreExecute(); mParams = params; mThread.start(); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/util/ColorGenerator.java ================================================ package moe.feng.nhentai.util; import java.util.Arrays; import java.util.List; import java.util.Random; /** * @author amulya * @datetime 14 Oct 2014, 5:20 PM */ public class ColorGenerator { public static ColorGenerator DEFAULT; public static ColorGenerator MATERIAL; static { DEFAULT = create(Arrays.asList( 0xfff16364, 0xfff58559, 0xfff9a43e, 0xffe4c62e, 0xff67bf74, 0xff59a2be, 0xff2093cd, 0xffad62a7, 0xff805781 )); MATERIAL = create(Arrays.asList( 0xffe57373, 0xfff06292, 0xffba68c8, 0xff9575cd, 0xff7986cb, 0xff64b5f6, 0xff4fc3f7, 0xff4dd0e1, 0xff4db6ac, 0xff81c784, 0xffaed581, 0xffff8a65, 0xffd4e157, 0xffffd54f, 0xffffb74d, 0xffa1887f, 0xff90a4ae )); } private final List mColors; private final Random mRandom; public static ColorGenerator create(List colorList) { return new ColorGenerator(colorList); } private ColorGenerator(List colorList) { mColors = colorList; mRandom = new Random(System.currentTimeMillis()); } public int getRandomColor() { return mColors.get(mRandom.nextInt(mColors.size())); } public int getColor(Object key) { return mColors.get(Math.abs(key.hashCode()) % mColors.size()); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/util/FullScreenHelper.java ================================================ package moe.feng.nhentai.util; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Build; import android.view.View; import android.view.ViewConfiguration; import android.view.Window; import android.view.WindowManager; @SuppressLint("InlinedApi") public final class FullScreenHelper implements View.OnSystemUiVisibilityChangeListener { private static final String TAG = FullScreenHelper.class.getSimpleName(); private final int NOT_FULL_SCREEN_JELLY_BEAN = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; private final int FULL_SCREEN_JELLY_BEAN = NOT_FULL_SCREEN_JELLY_BEAN | View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN; private final int FULL_SCREEN_FLAG_JELLY_BEAN = View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN; private final int NOT_FULL_SCREEN_KITKAT = NOT_FULL_SCREEN_JELLY_BEAN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; private final int FULL_SCREEN_KITKAT = NOT_FULL_SCREEN_KITKAT | View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; private boolean mFullScreen; private final Activity mActivity; private final Window mWindow; private final View mDecorView; private boolean mHasNavBar; private OnFullScreenBrokenListener mListener; private final int TEST_SDK = Build.VERSION.SDK_INT; public interface OnFullScreenBrokenListener { /** * FullScreen state should be fullScreen or not, * but user or system broke it * * @param fullScreen support to be */ public void onFullScreenBroken(boolean fullScreen); } public FullScreenHelper(Activity activity) { mFullScreen = false; mActivity = activity; mWindow = mActivity.getWindow(); mDecorView = mWindow.getDecorView(); mDecorView.setOnSystemUiVisibilityChangeListener(this); String mainKey = Utility.getSystemProperties("qemu.hw.mainkeys"); int resourceId = activity.getResources().getIdentifier("config_showNavigationBar", "bool", "android"); if (resourceId != 0) { mHasNavBar = activity.getResources().getBoolean(resourceId); // check override flag (see static block) if ("1".equals(mainKey)) { mHasNavBar = false; } else if ("0".equals(mainKey)) { mHasNavBar = true; } } else { mHasNavBar = !ViewConfiguration.get(activity).hasPermanentMenuKey(); } } public boolean willHideNavBar() { if (TEST_SDK >= Build.VERSION_CODES.KITKAT && mHasNavBar) return true; else return false; } @Override public void onSystemUiVisibilityChange(int visibility) { if (TEST_SDK >= Build.VERSION_CODES.JELLY_BEAN && TEST_SDK < Build.VERSION_CODES.KITKAT) { if ((mFullScreen && visibility != FULL_SCREEN_FLAG_JELLY_BEAN) || (!mFullScreen && visibility != 0)) { // User or system change visibility if (mListener != null) mListener.onFullScreenBroken(mFullScreen); } } } public void setOnFullScreenBrokenListener(OnFullScreenBrokenListener l) { mListener = l; } public boolean getFullScreen() { return mFullScreen; } public void setFullScreen(boolean fullScreen) { mFullScreen = fullScreen; if (fullScreen) { if (TEST_SDK < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // Empty } else if (TEST_SDK < Build.VERSION_CODES.JELLY_BEAN) { mWindow.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } else if (TEST_SDK < Build.VERSION_CODES.KITKAT) { mDecorView.setSystemUiVisibility(FULL_SCREEN_JELLY_BEAN); } else { mDecorView.setSystemUiVisibility(FULL_SCREEN_KITKAT); } } else { if (TEST_SDK < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // Empty } else if (TEST_SDK < Build.VERSION_CODES.JELLY_BEAN) { mWindow.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else if (TEST_SDK < Build.VERSION_CODES.KITKAT) { mDecorView.setSystemUiVisibility(NOT_FULL_SCREEN_JELLY_BEAN); } else { mDecorView.setSystemUiVisibility(NOT_FULL_SCREEN_KITKAT); } } } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/util/HttpTools.java ================================================ package moe.feng.nhentai.util; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class HttpTools { public static HttpURLConnection openConnection(String url) throws IOException { URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept-Encoding", "identity"); conn.setRequestProperty("Referer", URLEncoder.encode(url, "UTF-8")); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Connection", "Keep-Alive"); return conn; } public static long getTargetContentSize(String url) throws IOException { HttpURLConnection conn = openConnection(url); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { return conn.getContentLength(); } return -1; } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/util/Settings.java ================================================ package moe.feng.nhentai.util; import android.content.Context; import moe.feng.nhentai.dao.CommonPreferences; public class Settings { public static final String PREFERENCES_NAME = "settings"; private static Settings sInstance; private CommonPreferences mPrefs; public static Settings getInstance(Context context) { if (sInstance == null) { sInstance = new Settings(context); } return sInstance; } private Settings(Context context) { mPrefs = CommonPreferences.getInstance(context, PREFERENCES_NAME); } public Settings putBoolean(String key, boolean value) { mPrefs.edit().putBoolean(key, value).commit(); return this; } public boolean getBoolean(String key, boolean def) { return mPrefs.getBoolean(key, def); } public Settings putInt(String key, int value) { mPrefs.edit().putInt(key, value).commit(); return this; } public int getInt(String key, int defValue) { return mPrefs.getInt(key, defValue); } public Settings putString(String key, String value) { mPrefs.edit().putString(key, value).commit(); return this; } public String getString(String key, String defValue) { return mPrefs.getString(key, defValue); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/util/TextDrawable.java ================================================ package moe.feng.nhentai.util; import android.graphics.*; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.graphics.drawable.shapes.RectShape; import android.graphics.drawable.shapes.RoundRectShape; /** * @author amulya * @datetime 14 Oct 2014, 3:53 PM */ public class TextDrawable extends ShapeDrawable { private final Paint textPaint; private final Paint borderPaint; private static final float SHADE_FACTOR = 0.9f; private final String text; private final int color; private final RectShape shape; private final int height; private final int width; private final int fontSize; private final float radius; private final int borderThickness; private TextDrawable(Builder builder) { super(builder.shape); // shape properties shape = builder.shape; height = builder.height; width = builder.width; radius = builder.radius; // text and color text = builder.toUpperCase ? builder.text.toUpperCase() : builder.text; color = builder.color; // text paint settings fontSize = builder.fontSize; textPaint = new Paint(); textPaint.setColor(builder.textColor); textPaint.setAntiAlias(true); textPaint.setFakeBoldText(builder.isBold); textPaint.setStyle(Paint.Style.FILL); textPaint.setTypeface(builder.font); textPaint.setTextAlign(Paint.Align.CENTER); textPaint.setStrokeWidth(builder.borderThickness); // border paint settings borderThickness = builder.borderThickness; borderPaint = new Paint(); borderPaint.setColor(getDarkerShade(color)); borderPaint.setStyle(Paint.Style.STROKE); borderPaint.setStrokeWidth(borderThickness); // drawable paint color Paint paint = getPaint(); paint.setColor(color); } private int getDarkerShade(int color) { return Color.rgb((int)(SHADE_FACTOR * Color.red(color)), (int)(SHADE_FACTOR * Color.green(color)), (int)(SHADE_FACTOR * Color.blue(color))); } @Override public void draw(Canvas canvas) { super.draw(canvas); Rect r = getBounds(); // draw border if (borderThickness > 0) { drawBorder(canvas); } int count = canvas.save(); canvas.translate(r.left, r.top); // draw text int width = this.width < 0 ? r.width() : this.width; int height = this.height < 0 ? r.height() : this.height; int fontSize = this.fontSize < 0 ? (Math.min(width, height) / 2) : this.fontSize; textPaint.setTextSize(fontSize); canvas.drawText(text, width / 2, height / 2 - ((textPaint.descent() + textPaint.ascent()) / 2), textPaint); canvas.restoreToCount(count); } private void drawBorder(Canvas canvas) { RectF rect = new RectF(getBounds()); rect.inset(borderThickness/2, borderThickness/2); if (shape instanceof OvalShape) { canvas.drawOval(rect, borderPaint); } else if (shape instanceof RoundRectShape) { canvas.drawRoundRect(rect, radius, radius, borderPaint); } else { canvas.drawRect(rect, borderPaint); } } @Override public void setAlpha(int alpha) { textPaint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter cf) { textPaint.setColorFilter(cf); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public int getIntrinsicWidth() { return width; } @Override public int getIntrinsicHeight() { return height; } public static IShapeBuilder builder() { return new Builder(); } public static class Builder implements IConfigBuilder, IShapeBuilder, IBuilder { private String text; private int color; private int borderThickness; private int width; private int height; private Typeface font; private RectShape shape; public int textColor; private int fontSize; private boolean isBold; private boolean toUpperCase; public float radius; private Builder() { text = ""; color = Color.GRAY; textColor = Color.WHITE; borderThickness = 0; width = -1; height = -1; shape = new RectShape(); font = Typeface.create("sans-serif-light", Typeface.NORMAL); fontSize = -1; isBold = false; toUpperCase = false; } public IConfigBuilder width(int width) { this.width = width; return this; } public IConfigBuilder height(int height) { this.height = height; return this; } public IConfigBuilder textColor(int color) { this.textColor = color; return this; } public IConfigBuilder withBorder(int thickness) { this.borderThickness = thickness; return this; } public IConfigBuilder useFont(Typeface font) { this.font = font; return this; } public IConfigBuilder fontSize(int size) { this.fontSize = size; return this; } public IConfigBuilder bold() { this.isBold = true; return this; } public IConfigBuilder toUpperCase() { this.toUpperCase = true; return this; } @Override public IConfigBuilder beginConfig() { return this; } @Override public IShapeBuilder endConfig() { return this; } @Override public IBuilder rect() { this.shape = new RectShape(); return this; } @Override public IBuilder round() { this.shape = new OvalShape(); return this; } @Override public IBuilder roundRect(int radius) { this.radius = radius; float[] radii = {radius, radius, radius, radius, radius, radius, radius, radius}; this.shape = new RoundRectShape(radii, null, null); return this; } @Override public TextDrawable buildRect(String text, int color) { rect(); return build(text, color); } @Override public TextDrawable buildRoundRect(String text, int color, int radius) { roundRect(radius); return build(text, color); } @Override public TextDrawable buildRound(String text, int color) { round(); return build(text, color); } @Override public TextDrawable build(String text, int color) { this.color = color; this.text = text; return new TextDrawable(this); } } public interface IConfigBuilder { public IConfigBuilder width(int width); public IConfigBuilder height(int height); public IConfigBuilder textColor(int color); public IConfigBuilder withBorder(int thickness); public IConfigBuilder useFont(Typeface font); public IConfigBuilder fontSize(int size); public IConfigBuilder bold(); public IConfigBuilder toUpperCase(); public IShapeBuilder endConfig(); } public static interface IBuilder { public TextDrawable build(String text, int color); } public static interface IShapeBuilder { public IConfigBuilder beginConfig(); public IBuilder rect(); public IBuilder round(); public IBuilder roundRect(int radius); public TextDrawable buildRect(String text, int color); public TextDrawable buildRoundRect(String text, int color, int radius); public TextDrawable buildRound(String text, int color); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/util/Utility.java ================================================ package moe.feng.nhentai.util; import android.content.Context; import android.os.Build; import java.lang.reflect.Method; public class Utility { public static boolean isChrome() { return Build.BRAND.equals("chromium") || Build.BRAND.equals("chrome"); } public static int getStatusBarHeight(Context context) { int result = 0; int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } return result; } public static String getFirstCharacter(String sentence) { for (int i = 0; i < sentence.length(); i++) { String s = sentence.substring(i, i+1); if (s.equals("[") || s.equals("]")) continue; if (s.equals("{") || s.equals("}")) continue; if (s.equals("(") || s.equals(")")) continue; if (s.equals(",") || s.equals(".")) continue; if (s.equals("<") || s.equals(">")) continue; if (s.equals("《") || s.equals("》")) continue; if (s.equals("【") || s.equals("】")) continue; if (s.equals("{") || s.equals("}")) continue; return s; } return null; } public static String getSystemProperties(String key) { try { Class c = Class.forName("android.os.SystemProperties"); Method m = c.getDeclaredMethod("get", String.class); m.setAccessible(true); return (String) m.invoke(null, key); } catch (Throwable e) { return ""; } } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/view/AutoWrapLayout.java ================================================ package moe.feng.nhentai.view; import java.util.ArrayList; import java.util.List; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import moe.feng.nhentai.R; /** * A ViewGroup that can layout views in line and auto wrap * * @author Hippo * */ public class AutoWrapLayout extends ViewGroup { @SuppressWarnings("unused") private final static String TAG = "AutoWrapLayout"; private final List rectList = new ArrayList(); private Alignment mAlignment; private static final Alignment[] sBaseLineArray = { Alignment.TOP, Alignment.CENTER, Alignment.BOTTOM }; public enum Alignment { TOP(0), CENTER(1), BOTTOM(2); Alignment(int ni) { nativeInt = ni; } final int nativeInt; } public AutoWrapLayout(Context context) { super(context); } public AutoWrapLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public AutoWrapLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AutoWrapLayout, defStyle, 0); int index = a.getInt(R.styleable.AutoWrapLayout_alignment, -1); if (index >= 0) setAlignment(sBaseLineArray[index]); a.recycle(); } public void setAlignment(Alignment baseLine) { if (baseLine == null) return; if (mAlignment != baseLine) { mAlignment = baseLine; requestLayout(); invalidate(); } } public Alignment getScaleType() { return mAlignment; } private void adjustBaseLine(int lineHeight, int startIndex, int endIndex) { if (mAlignment == Alignment.TOP) return; for (int index = startIndex; index < endIndex; index++) { final View child = getChildAt(index); final AutoWrapLayout.LayoutParams lp = (AutoWrapLayout.LayoutParams)child.getLayoutParams(); Rect rect = rectList.get(index); int offsetRaw = lineHeight - rect.height() - lp.topMargin - lp.bottomMargin; if (mAlignment == Alignment.CENTER) rect.offset(0, offsetRaw/2); else if (mAlignment == Alignment.BOTTOM) rect.offset(0, offsetRaw); } } // TODO Take vertical mode /** * each row or line at least show one child * * horizontal only show child can show or partly show in parent */ @SuppressLint("DrawAllocation") @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int maxWidth = MeasureSpec.getSize(widthMeasureSpec); int maxHeight = MeasureSpec.getSize(heightMeasureSpec); if (widthMode == MeasureSpec.UNSPECIFIED) maxWidth = Integer.MAX_VALUE; if (heightMode == MeasureSpec.UNSPECIFIED) maxHeight = Integer.MAX_VALUE; int paddingLeft = getPaddingLeft(); int paddingTop = getPaddingTop(); int paddingRight = getPaddingRight(); int paddingBottom = getPaddingBottom(); int maxRightBound = maxWidth - paddingRight; int maxBottomBound = maxHeight - paddingBottom; int left; int top; int right; int bottom; int rightBound = paddingLeft; int maxRightNoPadding = rightBound; int bottomBound; int lastMaxBottom = paddingTop; int maxBottom = lastMaxBottom; int childWidth; int childHeight; int lineStartIndex = 0; int lineEndIndex = 0; // endIndex + 1 rectList.clear(); int childCount = getChildCount(); for (int index = 0; index < childCount; index++) { final View child = getChildAt(index); child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); if (child.getVisibility() == View.GONE) continue; final AutoWrapLayout.LayoutParams lp = (AutoWrapLayout.LayoutParams)child.getLayoutParams(); childWidth = child.getMeasuredWidth(); childHeight = child.getMeasuredHeight(); left = rightBound + lp.leftMargin; right = left + childWidth; rightBound = right + lp.rightMargin; if (rightBound > maxRightBound) { // Go to next row lineEndIndex = index; // Adjust child position base on baseline adjustBaseLine(maxBottom - lastMaxBottom, lineStartIndex, lineEndIndex); // If child can't show in parent begin this line if (maxBottom >= maxBottomBound) break; // If it is first item in line, try to show it all if (lineEndIndex == lineStartIndex) { child.measure(MeasureSpec.makeMeasureSpec( maxWidth - paddingLeft - paddingRight - lp.leftMargin - lp.rightMargin, MeasureSpec.AT_MOST), MeasureSpec.UNSPECIFIED); childWidth = child.getMeasuredWidth(); childHeight = child.getMeasuredHeight(); } left = paddingLeft + lp.leftMargin; right = left + childWidth; rightBound = right + lp.rightMargin; lastMaxBottom = maxBottom; top = lastMaxBottom + lp.topMargin; bottom = top + childHeight; bottomBound = bottom + lp.bottomMargin; lineStartIndex = index; } else { top = lastMaxBottom + lp.topMargin; bottom = top + childHeight; bottomBound = bottom + lp.bottomMargin; } // Update max if (rightBound > maxRightNoPadding) maxRightNoPadding = rightBound; if (bottomBound > maxBottom) maxBottom = bottomBound; Rect rect = new Rect(); rect.left = left; rect.top = top; rect.right = right; rect.bottom = bottom; rectList.add(rect); } // Handle last line baseline adjustBaseLine(maxBottom - lastMaxBottom, lineStartIndex, rectList.size()); int measuredWidth; int measuredHeight; if (widthMode == MeasureSpec.EXACTLY) measuredWidth = maxWidth; else measuredWidth = maxRightNoPadding + paddingRight; if (heightMode == MeasureSpec.EXACTLY) measuredHeight = maxHeight; else { measuredHeight = maxBottom + paddingBottom; if (heightMode == MeasureSpec.AT_MOST) measuredHeight = measuredHeight > maxHeight ? maxHeight : measuredHeight; } setMeasuredDimension(measuredWidth, measuredHeight); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = rectList.size(); for(int i = 0; i < count; i++){ final View child = this.getChildAt(i); if (child.getVisibility() == View.GONE) continue; Rect rect = rectList.get(i); child.layout(rect.left, rect.top, rect.right, rect.bottom); } } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new AutoWrapLayout.LayoutParams(getContext(), attrs); } @Override protected LayoutParams generateDefaultLayoutParams() { return new AutoWrapLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } @Override protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return new LayoutParams(p); } public static class LayoutParams extends ViewGroup.MarginLayoutParams { public LayoutParams() { this(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); } public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(android.view.ViewGroup.LayoutParams source) { super(source); } public LayoutParams(MarginLayoutParams source) { super(source); } } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/view/ExpandableHeightGridView.java ================================================ package moe.feng.nhentai.view; import android.content.Context; import android.util.AttributeSet; import android.view.ViewGroup; import android.widget.GridView; public class ExpandableHeightGridView extends GridView { private boolean expanded = false; public ExpandableHeightGridView(Context context) { super(context); } public ExpandableHeightGridView(Context context, AttributeSet attrs) { super(context, attrs); } public ExpandableHeightGridView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public boolean isExpanded() { return expanded; } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (isExpanded()) { int expandSpec = MeasureSpec.makeMeasureSpec( Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); ViewGroup.LayoutParams params = getLayoutParams(); params.height = getMeasuredHeight(); } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } public void setExpanded(boolean expanded) { this.expanded = expanded; } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/view/WheelProgressView.java ================================================ package moe.feng.nhentai.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.RectF; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.View; import moe.feng.nhentai.R; /** * A Material style progress wheel, compatible up to 2.2. * Todd Davies' Progress Wheel https://github.com/Todd-Davies/ProgressWheel * * @author Nico Hormazabal *

* Licensed under the Apache License 2.0 license see: * http://www.apache.org/licenses/LICENSE-2.0 */ public class WheelProgressView extends View { private static final String TAG = WheelProgressView.class.getSimpleName(); private int circleRadius = 28; private int barWidth = 4; private int rimWidth = 4; private final int barLength = 16; private final int barMaxLength = 270; private boolean fillRadius = false; private double timeStartGrowing = 0; private double barSpinCycleTime = 460; private float barExtraLength = 0; private boolean barGrowingFromFront = true; private long pausedTimeWithoutGrowing = 0; private final long pauseGrowingTime = 200; private int barColor = 0xAA000000; private int rimColor = 0x00FFFFFF; private Paint barPaint = new Paint(); private Paint rimPaint = new Paint(); private RectF circleBounds = new RectF(); private float spinSpeed = 230.0f; private long lastTimeAnimated = 0; private boolean linearProgress; private float mProgress = 0.0f; private float mTargetProgress = 0.0f; private boolean isSpinning = false; private ProgressCallback callback; /** * The constructor for the ProgressWheel * * @param context * @param attrs */ public WheelProgressView(Context context, AttributeSet attrs) { super(context, attrs); parseAttributes(context.obtainStyledAttributes(attrs, R.styleable.WheelProgressView)); } /** * The constructor for the ProgressWheel * * @param context */ public WheelProgressView(Context context) { super(context); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int viewWidth = circleRadius + this.getPaddingLeft() + this.getPaddingRight(); int viewHeight = circleRadius + this.getPaddingTop() + this.getPaddingBottom(); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width; int height; if (widthMode == MeasureSpec.EXACTLY) { width = widthSize; } else if (widthMode == MeasureSpec.AT_MOST) { width = Math.min(viewWidth, widthSize); } else { width = viewWidth; } if (heightMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.EXACTLY) { height = heightSize; } else if (heightMode == MeasureSpec.AT_MOST) { height = Math.min(viewHeight, heightSize); } else { height = viewHeight; } setMeasuredDimension(width, height); } /** * Use onSizeChanged instead of onAttachedToWindow to get the dimensions of the view, * because this method is called after measuring the dimensions of MATCH_PARENT & WRAP_CONTENT. * Use this dimensions to setup the bounds and paints. */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); setupBounds(w, h); setupPaints(); invalidate(); } /** * Set the properties of the paints we're using to * draw the progress wheel */ private void setupPaints() { barPaint.setColor(barColor); barPaint.setAntiAlias(true); barPaint.setStyle(Style.STROKE); barPaint.setStrokeWidth(barWidth); rimPaint.setColor(rimColor); rimPaint.setAntiAlias(true); rimPaint.setStyle(Style.STROKE); rimPaint.setStrokeWidth(rimWidth); } /** * Set the bounds of the component */ private void setupBounds(int layout_width, int layout_height) { int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); if (!fillRadius) { int minValue = Math.min(layout_width - paddingLeft - paddingRight, layout_height - paddingBottom - paddingTop); int circleDiameter = Math.min(minValue, circleRadius * 2 - barWidth * 2); int xOffset = (layout_width - paddingLeft - paddingRight - circleDiameter) / 2 + paddingLeft; int yOffset = (layout_height - paddingTop - paddingBottom - circleDiameter) / 2 + paddingTop; circleBounds = new RectF(xOffset + barWidth, yOffset + barWidth, xOffset + circleDiameter - barWidth, yOffset + circleDiameter - barWidth); } else { circleBounds = new RectF(paddingLeft + barWidth, paddingTop + barWidth, layout_width - paddingRight - barWidth, layout_height - paddingBottom - barWidth); } } /** * Parse the attributes passed to the view from the XML * * @param a the attributes to parse */ private void parseAttributes(TypedArray a) { DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); barWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, barWidth, metrics); rimWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rimWidth, metrics); circleRadius = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, circleRadius, metrics); circleRadius = (int) a.getDimension(R.styleable.WheelProgressView_matProg_circleRadius, circleRadius); fillRadius = a.getBoolean(R.styleable.WheelProgressView_matProg_fillRadius, false); barWidth = (int) a.getDimension(R.styleable.WheelProgressView_matProg_barWidth, barWidth); rimWidth = (int) a.getDimension(R.styleable.WheelProgressView_matProg_rimWidth, rimWidth); float baseSpinSpeed = a.getFloat(R.styleable.WheelProgressView_matProg_spinSpeed, spinSpeed / 360.0f); spinSpeed = baseSpinSpeed * 360; barSpinCycleTime = a.getInt(R.styleable.WheelProgressView_matProg_barSpinCycleTime, (int) barSpinCycleTime); barColor = a.getColor(R.styleable.WheelProgressView_matProg_barColor, barColor); rimColor = a.getColor(R.styleable.WheelProgressView_matProg_rimColor, rimColor); linearProgress = a.getBoolean(R.styleable.WheelProgressView_matProg_linearProgress, false); if (a.getBoolean(R.styleable.WheelProgressView_matProg_progressIndeterminate, false)) { spin(); } a.recycle(); } public void setCallback(ProgressCallback progressCallback) { callback = progressCallback; if (!isSpinning) { runCallback(); } } protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawArc(circleBounds, 360, 360, false, rimPaint); boolean mustInvalidate = false; if (isSpinning) { mustInvalidate = true; long deltaTime = (SystemClock.uptimeMillis() - lastTimeAnimated); float deltaNormalized = deltaTime * spinSpeed / 1000.0f; updateBarLength(deltaTime); mProgress += deltaNormalized; if (mProgress > 360) { mProgress -= 360f; runCallback(-1.0f); } lastTimeAnimated = SystemClock.uptimeMillis(); float from = mProgress - 90; float length = barLength + barExtraLength; if (isInEditMode()) { from = 0; length = 135; } canvas.drawArc(circleBounds, from, length, false, barPaint); } else { float oldProgress = mProgress; if (mProgress != mTargetProgress) { mustInvalidate = true; float deltaTime = (float) (SystemClock.uptimeMillis() - lastTimeAnimated) / 1000; float deltaNormalized = deltaTime * spinSpeed; mProgress = Math.min(mProgress + deltaNormalized, mTargetProgress); lastTimeAnimated = SystemClock.uptimeMillis(); } if (oldProgress != mProgress) { runCallback(); } float offset = 0.0f; float progress = mProgress; if (!linearProgress) { float factor = 2.0f; offset = (float) (1.0f - Math.pow(1.0f - mProgress / 360.0f, 2.0f * factor)) * 360.0f; progress = (float) (1.0f - Math.pow(1.0f - mProgress / 360.0f, factor)) * 360.0f; } if (isInEditMode()) { progress = 360; } canvas.drawArc(circleBounds, offset - 90, progress, false, barPaint); } if (mustInvalidate) { invalidate(); } } @Override protected void onVisibilityChanged(@NonNull View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if (visibility == VISIBLE) { lastTimeAnimated = SystemClock.uptimeMillis(); } } private void updateBarLength(long deltaTimeInMilliSeconds) { if (pausedTimeWithoutGrowing >= pauseGrowingTime) { timeStartGrowing += deltaTimeInMilliSeconds; if (timeStartGrowing > barSpinCycleTime) { timeStartGrowing -= barSpinCycleTime; pausedTimeWithoutGrowing = 0; barGrowingFromFront = !barGrowingFromFront; } float distance = (float) Math.cos((timeStartGrowing / barSpinCycleTime + 1) * Math.PI) / 2 + 0.5f; float destLength = (barMaxLength - barLength); if (barGrowingFromFront) { barExtraLength = distance * destLength; } else { float newLength = destLength * (1 - distance); mProgress += (barExtraLength - newLength); barExtraLength = newLength; } } else { pausedTimeWithoutGrowing += deltaTimeInMilliSeconds; } } /** * Check if the wheel is currently spinning */ public boolean isSpinning() { return isSpinning; } /** * Reset the count (in increment mode) */ public void resetCount() { mProgress = 0.0f; mTargetProgress = 0.0f; invalidate(); } /** * Turn off spin mode */ public void stopSpinning() { isSpinning = false; mProgress = 0.0f; mTargetProgress = 0.0f; invalidate(); } /** * Puts the view on spin mode */ public void spin() { lastTimeAnimated = SystemClock.uptimeMillis(); isSpinning = true; invalidate(); } private void runCallback(float value) { if (callback != null) { callback.onProgressUpdate(value); } } private void runCallback() { if (callback != null) { float normalizedProgress = (float) Math.round(mProgress * 100 / 360.0f) / 100; callback.onProgressUpdate(normalizedProgress); } } /** * Set the progress to a specific value, * the bar will smoothly animate until that value * * @param progress the progress between 0 and 1 */ public void setProgress(float progress) { if (isSpinning) { mProgress = 0.0f; isSpinning = false; runCallback(); } if (progress > 1.0f) { progress -= 1.0f; } else if (progress < 0) { progress = 0; } if (progress == mTargetProgress) { return; } if (mProgress == mTargetProgress) { lastTimeAnimated = SystemClock.uptimeMillis(); } mTargetProgress = Math.min(progress * 360.0f, 360.0f); invalidate(); } /** * Set the progress to a specific value, * the bar will be set instantly to that value * * @param progress the progress between 0 and 1 */ public void setInstantProgress(float progress) { if (isSpinning) { mProgress = 0.0f; isSpinning = false; } if (progress > 1.0f) { progress -= 1.0f; } else if (progress < 0) { progress = 0; } if (progress == mTargetProgress) { return; } mTargetProgress = Math.min(progress * 360.0f, 360.0f); mProgress = mTargetProgress; lastTimeAnimated = SystemClock.uptimeMillis(); invalidate(); } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); WheelSavedState ss = new WheelSavedState(superState); ss.mProgress = this.mProgress; ss.mTargetProgress = this.mTargetProgress; ss.isSpinning = this.isSpinning; ss.spinSpeed = this.spinSpeed; ss.barWidth = this.barWidth; ss.barColor = this.barColor; ss.rimWidth = this.rimWidth; ss.rimColor = this.rimColor; ss.circleRadius = this.circleRadius; ss.linearProgress = this.linearProgress; ss.fillRadius = this.fillRadius; return ss; } @Override public void onRestoreInstanceState(Parcelable state) { if (!(state instanceof WheelSavedState)) { super.onRestoreInstanceState(state); return; } WheelSavedState ss = (WheelSavedState) state; super.onRestoreInstanceState(ss.getSuperState()); this.mProgress = ss.mProgress; this.mTargetProgress = ss.mTargetProgress; this.isSpinning = ss.isSpinning; this.spinSpeed = ss.spinSpeed; this.barWidth = ss.barWidth; this.barColor = ss.barColor; this.rimWidth = ss.rimWidth; this.rimColor = ss.rimColor; this.circleRadius = ss.circleRadius; this.linearProgress = ss.linearProgress; this.fillRadius = ss.fillRadius; this.lastTimeAnimated = SystemClock.uptimeMillis(); } /** * @return the current progress between 0.0 and 1.0, * if the wheel is indeterminate, then the result is -1 */ public float getProgress() { return isSpinning ? -1 : mProgress / 360.0f; } /** * Sets the determinate progress mode * * @param isLinear if the progress should increase linearly */ public void setLinearProgress(boolean isLinear) { linearProgress = isLinear; if (!isSpinning) { invalidate(); } } /** * @return the radius of the wheel in pixels */ public int getCircleRadius() { return circleRadius; } /** * Sets the radius of the wheel * * @param circleRadius the expected radius, in pixels */ public void setCircleRadius(int circleRadius) { this.circleRadius = circleRadius; if (!isSpinning) { invalidate(); } } /** * @return the width of the spinning bar */ public int getBarWidth() { return barWidth; } /** * Sets the width of the spinning bar * * @param barWidth the spinning bar width in pixels */ public void setBarWidth(int barWidth) { this.barWidth = barWidth; if (!isSpinning) { invalidate(); } } /** * @return the color of the spinning bar */ public int getBarColor() { return barColor; } /** * Sets the color of the spinning bar * * @param barColor The spinning bar color */ public void setBarColor(int barColor) { this.barColor = barColor; setupPaints(); if (!isSpinning) { invalidate(); } } /** * @return the color of the wheel's contour */ public int getRimColor() { return rimColor; } /** * Sets the color of the wheel's contour * * @param rimColor the color for the wheel */ public void setRimColor(int rimColor) { this.rimColor = rimColor; setupPaints(); if (!isSpinning) { invalidate(); } } /** * @return the base spinning speed, in full circle turns per second * (1.0 equals on full turn in one second), this value also is applied for * the smoothness when setting a progress */ public float getSpinSpeed() { return spinSpeed / 360.0f; } /** * Sets the base spinning speed, in full circle turns per second * (1.0 equals on full turn in one second), this value also is applied for * the smoothness when setting a progress * * @param spinSpeed the desired base speed in full turns per second */ public void setSpinSpeed(float spinSpeed) { this.spinSpeed = spinSpeed * 360.0f; } /** * @return the width of the wheel's contour in pixels */ public int getRimWidth() { return rimWidth; } /** * Sets the width of the wheel's contour * * @param rimWidth the width in pixels */ public void setRimWidth(int rimWidth) { this.rimWidth = rimWidth; if (!isSpinning) { invalidate(); } } static class WheelSavedState extends BaseSavedState { float mProgress; float mTargetProgress; boolean isSpinning; float spinSpeed; int barWidth; int barColor; int rimWidth; int rimColor; int circleRadius; boolean linearProgress; boolean fillRadius; WheelSavedState(Parcelable superState) { super(superState); } private WheelSavedState(Parcel in) { super(in); this.mProgress = in.readFloat(); this.mTargetProgress = in.readFloat(); this.isSpinning = in.readByte() != 0; this.spinSpeed = in.readFloat(); this.barWidth = in.readInt(); this.barColor = in.readInt(); this.rimWidth = in.readInt(); this.rimColor = in.readInt(); this.circleRadius = in.readInt(); this.linearProgress = in.readByte() != 0; this.fillRadius = in.readByte() != 0; } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeFloat(this.mProgress); out.writeFloat(this.mTargetProgress); out.writeByte((byte) (isSpinning ? 1 : 0)); out.writeFloat(this.spinSpeed); out.writeInt(this.barWidth); out.writeInt(this.barColor); out.writeInt(this.rimWidth); out.writeInt(this.rimColor); out.writeInt(this.circleRadius); out.writeByte((byte) (linearProgress ? 1 : 0)); out.writeByte((byte) (fillRadius ? 1 : 0)); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public WheelSavedState createFromParcel(Parcel in) { return new WheelSavedState(in); } public WheelSavedState[] newArray(int size) { return new WheelSavedState[size]; } }; } public interface ProgressCallback { /** * Method to call when the progress reaches a value * in order to avoid float precision issues, the progress * is rounded to a float with two decimals. * * In indeterminate mode, the callback is called each time * the wheel completes an animation cycle, with, the progress value is -1.0f * * @param progress a double value between 0.00 and 1.00 both included */ public void onProgressUpdate(float progress); } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/view/pref/Preference.java ================================================ package moe.feng.nhentai.view.pref; import android.annotation.TargetApi; import android.content.Context; import android.os.Build.VERSION_CODES; import android.util.AttributeSet; import moe.feng.nhentai.R; public class Preference extends android.preference.Preference { private boolean _isInitialized = false; protected void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { setLayoutResource(R.layout.custom_preference); } @TargetApi(VERSION_CODES.LOLLIPOP) public Preference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); if (!_isInitialized) { _isInitialized = true; init(context, attrs, defStyleAttr, defStyleRes); } } public Preference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); if (!_isInitialized) { _isInitialized = true; init(context, attrs, defStyleAttr, 0); } } public Preference(Context context, AttributeSet attrs) { super(context, attrs); if (!_isInitialized) { _isInitialized = true; init(context, attrs, 0, 0); } } public Preference(Context context) { super(context); if (!_isInitialized) { _isInitialized = true; init(context, null, 0, 0); } } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/view/pref/SwitchPreference.java ================================================ package moe.feng.nhentai.view.pref; import android.content.Context; import android.content.res.TypedArray; import android.support.v7.widget.SwitchCompat; import android.util.AttributeSet; import android.view.View; import android.widget.Checkable; import android.widget.CompoundButton; import moe.feng.nhentai.R; /** * A {@link Preference} that provides a two-state toggleable option. *

* This preference will store a boolean into the SharedPreferences. * * @attr ref android.R.styleable#SwitchPreference_summaryOff * @attr ref android.R.styleable#SwitchPreference_summaryOn * @attr ref android.R.styleable#SwitchPreference_switchTextOff * @attr ref android.R.styleable#SwitchPreference_switchTextOn * @attr ref android.R.styleable#SwitchPreference_disableDependentsState */ public class SwitchPreference extends TwoStatePreference { private final Listener mListener = new Listener(); private CharSequence mSwitchOn; private CharSequence mSwitchOff; private class Listener implements CompoundButton.OnCheckedChangeListener { @Override public void onCheckedChanged (CompoundButton buttonView, boolean isChecked) { if (!callChangeListener(isChecked)) { buttonView.setChecked(!isChecked); return; } SwitchPreference.this.setChecked(isChecked); } } /** * Construct a new SwitchPreference with the given style options. * * @param context The Context that will style this preference * @param attrs Style attributes that differ from the default * @param defStyleAttr An attribute in the current theme that contains a * reference to a style resource that supplies default values for * the view. Can be 0 to not look for defaults. * @param defStyleRes A resource identifier of a style resource that * supplies default values for the view, used only if * defStyleAttr is 0 or can not be found in the theme. Can be 0 * to not look for defaults. */ public SwitchPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } /** * Construct a new SwitchPreference with the given style options. * * @param context The Context that will style this preference * @param attrs Style attributes that differ from the default * @param defStyleAttr An attribute in the current theme that contains a * reference to a style resource that supplies default values for * the view. Can be 0 to not look for defaults. */ public SwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } /** * Construct a new SwitchPreference with the given style options. * * @param context The Context that will style this preference * @param attrs Style attributes that differ from the default */ public SwitchPreference(Context context,AttributeSet attrs) { this(context, attrs, R.attr.switchPreferenceStyle); } /** * Construct a new SwitchPreference with default style options. * * @param context The Context that will style this preference */ public SwitchPreference(Context context) { this(context, null); } @Override protected void init(final Context context,final AttributeSet attrs,final int defStyleAttr,final int defStyleRes) { super.init(context,attrs,defStyleAttr,defStyleRes); this.setWidgetLayoutResource(R.layout.custom_preference_widget_switch); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwitchPreference, defStyleAttr, defStyleRes); setSummaryOn(a.getString(R.styleable.SwitchPreference_summaryOn)); setSummaryOff(a.getString(R.styleable.SwitchPreference_summaryOff)); setSwitchTextOn(a.getString(R.styleable.SwitchPreference_switchTextOn)); setSwitchTextOff(a.getString(R.styleable.SwitchPreference_switchTextOff)); setDisableDependentsState(a.getBoolean(R.styleable.SwitchPreference_disableDependentsState, false)); a.recycle(); } @Override protected void onBindView(View view) { super.onBindView(view); View checkableView = view.findViewById(android.R.id.checkbox); if (checkableView != null && checkableView instanceof Checkable) { if (checkableView instanceof SwitchCompat) { final SwitchCompat switchView = (SwitchCompat) checkableView; switchView.setOnCheckedChangeListener(null); } ((Checkable) checkableView).setChecked(mChecked); if (checkableView instanceof SwitchCompat) { final SwitchCompat switchView = (SwitchCompat) checkableView; switchView.setTextOn(mSwitchOn); switchView.setTextOff(mSwitchOff); switchView.setOnCheckedChangeListener(mListener); } } syncSummaryView(view); } /** * Set the text displayed on the switch widget in the on state. * This should be a very short string; one word if possible. * * @param onText Text to display in the on state */ public void setSwitchTextOn(CharSequence onText) { mSwitchOn = onText; notifyChanged(); } /** * Set the text displayed on the switch widget in the off state. * This should be a very short string; one word if possible. * * @param offText Text to display in the off state */ public void setSwitchTextOff(CharSequence offText) { mSwitchOff = offText; notifyChanged(); } /** * Set the text displayed on the switch widget in the on state. * This should be a very short string; one word if possible. * * @param resId The text as a string resource ID */ public void setSwitchTextOn(int resId) { setSwitchTextOn(getContext().getString(resId)); } /** * Set the text displayed on the switch widget in the off state. * This should be a very short string; one word if possible. * * @param resId The text as a string resource ID */ public void setSwitchTextOff(int resId) { setSwitchTextOff(getContext().getString(resId)); } /** * @return The text that will be displayed on the switch widget in the on state */ public CharSequence getSwitchTextOn() { return mSwitchOn; } /** * @return The text that will be displayed on the switch widget in the off state */ public CharSequence getSwitchTextOff() { return mSwitchOff; } } ================================================ FILE: app/src/main/java/moe/feng/nhentai/view/pref/TwoStatePreference.java ================================================ package moe.feng.nhentai.view.pref; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; /** * Common base class for preferences that have two selectable states, persist a * boolean value in SharedPreferences, and may have dependent preferences that are * enabled/disabled based on the current state. */ public abstract class TwoStatePreference extends Preference { private CharSequence mSummaryOn; private CharSequence mSummaryOff; boolean mChecked; private boolean mCheckedSet; private boolean mDisableDependentsState; public TwoStatePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public TwoStatePreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public TwoStatePreference(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TwoStatePreference(Context context) { this(context, null); } @Override protected void onClick() { super.onClick(); final boolean newValue = !isChecked(); if (callChangeListener(newValue)) { setChecked(newValue); } } /** * Sets the checked state and saves it to the {@link SharedPreferences}. * * @param checked The checked state. */ public void setChecked(boolean checked) { final boolean changed = mChecked != checked; if (changed || !mCheckedSet) { mChecked = checked; mCheckedSet = true; persistBoolean(checked); if (changed) { notifyDependencyChange(shouldDisableDependents()); notifyChanged(); } } } /** * Returns the checked state. * * @return The checked state. */ public boolean isChecked() { return mChecked; } @Override public boolean shouldDisableDependents() { boolean shouldDisable = mDisableDependentsState?mChecked:!mChecked; return shouldDisable || super.shouldDisableDependents(); } /** * Sets the summary to be shown when checked. * * @param summary The summary to be shown when checked. */ public void setSummaryOn(CharSequence summary) { mSummaryOn = summary; if (isChecked()) { notifyChanged(); } } /** * @param summaryResId The summary as a resource. * @see #setSummaryOn(CharSequence) */ public void setSummaryOn(int summaryResId) { setSummaryOn(getContext().getString(summaryResId)); } /** * Returns the summary to be shown when checked. * * @return The summary. */ public CharSequence getSummaryOn() { return mSummaryOn; } /** * Sets the summary to be shown when unchecked. * * @param summary The summary to be shown when unchecked. */ public void setSummaryOff(CharSequence summary) { mSummaryOff = summary; if (!isChecked()) { notifyChanged(); } } /** * @param summaryResId The summary as a resource. * @see #setSummaryOff(CharSequence) */ public void setSummaryOff(int summaryResId) { setSummaryOff(getContext().getString(summaryResId)); } /** * Returns the summary to be shown when unchecked. * * @return The summary. */ public CharSequence getSummaryOff() { return mSummaryOff; } /** * Returns whether dependents are disabled when this preference is on ({@code true}) * or when this preference is off ({@code false}). * * @return Whether dependents are disabled when this preference is on ({@code true}) * or when this preference is off ({@code false}). */ public boolean getDisableDependentsState() { return mDisableDependentsState; } /** * Sets whether dependents are disabled when this preference is on ({@code true}) * or when this preference is off ({@code false}). * * @param disableDependentsState The preference state that should disable dependents. */ public void setDisableDependentsState(boolean disableDependentsState) { mDisableDependentsState = disableDependentsState; } @Override protected Object onGetDefaultValue(TypedArray a,int index) { return a.getBoolean(index, false); } @Override protected void onSetInitialValue(boolean restoreValue,Object defaultValue) { setChecked(restoreValue ? getPersistedBoolean(mChecked) : (Boolean) defaultValue); } /** * Sync a summary view contained within view's subhierarchy with the correct summary text. * * @param view View where a summary should be located */ void syncSummaryView(View view) { TextView summaryView = (TextView) view.findViewById(android.R.id.summary); if (summaryView != null) { boolean useDefaultSummary = true; if (mChecked && !TextUtils.isEmpty(mSummaryOn)) { summaryView.setText(mSummaryOn); useDefaultSummary = false; } else if (!mChecked && !TextUtils.isEmpty(mSummaryOff)) { summaryView.setText(mSummaryOff); useDefaultSummary = false; } if (useDefaultSummary) { final CharSequence summary = getSummary(); if (!TextUtils.isEmpty(summary)) { summaryView.setText(summary); useDefaultSummary = false; } } int newVisibility = View.GONE; if (!useDefaultSummary) { newVisibility = View.VISIBLE; } if (newVisibility != summaryView.getVisibility()) { summaryView.setVisibility(newVisibility); } } } @Override protected Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); if (isPersistent()) { return superState; } final SavedState myState = new SavedState(superState); myState.checked = isChecked(); return myState; } @Override protected void onRestoreInstanceState(Parcelable state) { if (state == null || !state.getClass().equals(SavedState.class)) { super.onRestoreInstanceState(state); return; } SavedState myState = (SavedState) state; super.onRestoreInstanceState(myState.getSuperState()); setChecked(myState.checked); } static class SavedState extends BaseSavedState { boolean checked; public SavedState(Parcel source) { super(source); checked = source.readInt() == 1; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(checked ? 1 : 0); } public SavedState(Parcelable superState) { super(superState); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } } ================================================ FILE: app/src/main/java/sumimakito/android/quickkv/DataProcessor.java ================================================ /** * QucikKV * Copyright (c) 2014-2015 Sumi Makito * Licensed under Apache License 2.0. * @author sumimakito * @version 0.8.2 */ package sumimakito.android.quickkv; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class DataProcessor { public static class Persistable { public static Object dePrefix(String k) throws JSONException { if (k.startsWith("String_")) { return k.substring("String_".length()); } else if (k.startsWith("Boolean_")) { return Boolean.parseBoolean(k.substring("Boolean_".length())); } else if (k.startsWith("Integer_")) { return Integer.parseInt(k.substring("Integer_".length())); } else if (k.startsWith("Float_")) { return Float.parseFloat(k.substring("Float_".length())); } else if (k.startsWith("Double_")) { return Double.parseDouble(k.substring("Double_".length())); } else if (k.startsWith("Long_")) { return Long.parseLong(k.substring("Long_".length())); } else if (k.startsWith("JSONArray_")) { return new JSONArray(k.substring("JSONArray_".length())); } else if (k.startsWith("JSONObject_")) { return new JSONObject(k.substring("JSONObject_".length())); } else { return null; } } public static boolean isValidDataType(Object obj) { if (obj instanceof String || obj instanceof Integer || obj instanceof Boolean || obj instanceof Long || obj instanceof Float || obj instanceof Double || obj instanceof JSONObject || obj instanceof JSONArray) { return true; } else { return false; } } public static String addPrefix(Object obj) { if (obj instanceof String) { return "String_" + obj.toString(); } else if (obj instanceof Integer) { return "Integer_" + obj.toString(); } else if (obj instanceof Boolean) { return "Boolean_" + obj.toString(); } else if (obj instanceof Long) { return "Long_" + obj.toString(); } else if (obj instanceof Float) { return "Float_" + obj.toString(); } else if (obj instanceof Double) { return "Double_" + obj.toString(); } else if (obj instanceof org.json.JSONObject) { return "JSONObject_" + obj.toString(); } else if (obj instanceof org.json.JSONArray) { return "JSONArray_" + obj.toString(); } else { return obj.toString(); } } } } ================================================ FILE: app/src/main/java/sumimakito/android/quickkv/QKVConfig.java ================================================ /** * QucikKV * Copyright (c) 2014-2015 Sumi Makito * Licensed under Apache License 2.0. * @author sumimakito * @version 0.8.2 */ package sumimakito.android.quickkv; public class QKVConfig { public static final boolean DEBUG = false; //Change it to true in development mode. public static final String PUBLIC_LTAG = "QuickKV"; //Default log tag. There is no need to change it. public static final String KVDB_FILE_NAME = "database.qkv"; //Default KVDB filename public static final String KVDB_NAME = "database"; //Name (must match above) public static final String KVDB_EXT = ".qkv"; //Ext (must match above above) public static final String EC_PREFIX = "__QKVEC_"; // :-/ Abandoned } ================================================ FILE: app/src/main/java/sumimakito/android/quickkv/QKVFSReader.java ================================================ /** * QucikKV * Copyright (c) 2014-2015 Sumi Makito * Licensed under Apache License 2.0. * @author sumimakito * @version 0.8.2 */ package sumimakito.android.quickkv; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.RandomAccessFile; import java.io.StringReader; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; public class QKVFSReader { public static String readFileBFD(String pFileAbsPath) throws IOException { return bfd(pFileAbsPath); } public static String readFileNIO(String pFileAbsPath) throws IOException{ return nio(pFileAbsPath); } private static String bfd(String pFilePath) throws FileNotFoundException,IOException{ BufferedReader bufferedReader = new BufferedReader(new FileReader(pFilePath)); StringBuilder sb = new StringBuilder(); String str = null; while((str = bufferedReader.readLine()) != null){ sb.append(str); } return sb.toString(); } private static String nio(String pFilePath) throws FileNotFoundException,IOException{ RandomAccessFile file = new RandomAccessFile(pFilePath, "r"); FileChannel fileChannel = file.getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect((int) fileChannel.size()); fileChannel.read(buffer); buffer.flip(); CharBuffer charBuffer = Charset.forName("utf-8").decode(buffer); file.close(); BufferedReader bufferedReader = new BufferedReader(new StringReader(charBuffer.toString())); StringBuilder sb = new StringBuilder(); String str = null; while((str = bufferedReader.readLine()) != null){ sb.append(str); } return sb.toString(); } } ================================================ FILE: app/src/main/java/sumimakito/android/quickkv/QKVLogger.java ================================================ /** * QucikKV * Copyright (c) 2014-2015 Sumi Makito * Licensed under Apache License 2.0. * @author sumimakito * @version 0.8.2 */ package sumimakito.android.quickkv; import android.util.Log; public class QKVLogger { public static void log(String level, String msg) { if (QKVConfig.DEBUG) { if (level.equals("i")) { Log.i(QKVConfig.PUBLIC_LTAG, msg); } else if (level.equals("w")) { Log.w(QKVConfig.PUBLIC_LTAG, msg); } } } public static void ex(Exception e) { if (QKVConfig.DEBUG) { e.printStackTrace(); } } } ================================================ FILE: app/src/main/java/sumimakito/android/quickkv/QuickKV.java ================================================ /** * QucikKV * Copyright (c) 2014-2015 Sumi Makito * Licensed under Apache License 2.0. * @author sumimakito * @version 0.8.2 */ package sumimakito.android.quickkv; import android.content.Context; import java.util.HashMap; import sumimakito.android.quickkv.database.KeyValueDatabase; public class QuickKV { private Context pContext; private HashMap sKVDB; public QuickKV(Context context) { this.pContext = context; this.sKVDB = new HashMap(); } public KeyValueDatabase getDatabase() { if (!this.sKVDB.containsKey(QKVConfig.KVDB_FILE_NAME)) { this.sKVDB.put(QKVConfig.KVDB_FILE_NAME, new KeyValueDatabase(pContext)); } return this.sKVDB.get(QKVConfig.KVDB_FILE_NAME); } public KeyValueDatabase getDatabase(String dbAlias) { if (dbAlias.equals(QKVConfig.KVDB_NAME) || dbAlias.equals(QKVConfig.KVDB_FILE_NAME)) { return getDatabase(); } if (dbAlias == null) { return null; } else { if (dbAlias.length() == 0) { dbAlias = QKVConfig.KVDB_FILE_NAME; } dbAlias = dbAlias.endsWith(QKVConfig.KVDB_EXT) ?dbAlias: dbAlias + QKVConfig.KVDB_EXT; } if (!this.sKVDB.containsKey(dbAlias)) { this.sKVDB.put(dbAlias, new KeyValueDatabase(pContext, dbAlias)); } return this.sKVDB.get(dbAlias); } public KeyValueDatabase getDatabase(String dbAlias, String key) { if (dbAlias.equals(QKVConfig.KVDB_NAME) || dbAlias.equals(QKVConfig.KVDB_FILE_NAME)) { return getDatabase(); } if (dbAlias == null) { return null; } else { if (dbAlias.length() == 0) { dbAlias = QKVConfig.KVDB_FILE_NAME; } dbAlias = dbAlias.endsWith(QKVConfig.KVDB_EXT) ?dbAlias: dbAlias + QKVConfig.KVDB_EXT; } if (!this.sKVDB.containsKey(dbAlias)) { this.sKVDB.put(dbAlias, new KeyValueDatabase(pContext, dbAlias, key)); } return this.sKVDB.get(dbAlias); } public boolean isDatabaseOpened() { return this.sKVDB.containsKey(QKVConfig.KVDB_FILE_NAME); } public boolean isDatabaseOpened(String dbAlias) { if (dbAlias.equals(QKVConfig.KVDB_NAME) || dbAlias.equals(QKVConfig.KVDB_FILE_NAME)) { return isDatabaseOpened(); } if (dbAlias == null) { return false; } else { if (dbAlias.length() == 0) { dbAlias = QKVConfig.KVDB_FILE_NAME; } dbAlias = dbAlias.endsWith(QKVConfig.KVDB_EXT) ?dbAlias: dbAlias + QKVConfig.KVDB_EXT; } return this.sKVDB.containsKey(dbAlias); } public boolean releaseDatabase() { if (isDatabaseOpened()) { this.sKVDB.remove(QKVConfig.KVDB_FILE_NAME); return true; } return false; } public boolean releaseDatabase(String dbAlias) { if (isDatabaseOpened(dbAlias)) { dbAlias = dbAlias.endsWith(QKVConfig.KVDB_EXT) ?dbAlias: dbAlias + QKVConfig.KVDB_EXT; this.sKVDB.remove(dbAlias); return true; } return false; } public void releaseAllDatabases() { this.sKVDB.clear(); } } ================================================ FILE: app/src/main/java/sumimakito/android/quickkv/database/KeyValueDatabase.java ================================================ /** * QucikKV * Copyright (c) 2014-2015 Sumi Makito * Licensed under Apache License 2.0. * @author sumimakito * @version 0.8.2 */ package sumimakito.android.quickkv.database; import android.content.*; import org.json.JSONObject; import java.io.*; import java.util.*; import sumimakito.android.quickkv.*; import sumimakito.android.quickkv.security.*; public class KeyValueDatabase implements QKVDatabase { private HashMap dMap; private Context pContext; private String dbAlias; private String pKey; public KeyValueDatabase(Context context) { this.pContext = context; this.dbAlias = QKVConfig.KVDB_FILE_NAME; this.dMap = new HashMap(); this.sync(false); QKVLogger.log("i", "KVDB Initialized!"); } public KeyValueDatabase(Context context, String dbAlias) { this.pContext = context; this.dbAlias = dbAlias.endsWith(QKVConfig.KVDB_EXT) ?dbAlias: dbAlias + QKVConfig.KVDB_EXT; this.dMap = new HashMap(); this.sync(false); QKVLogger.log("i", "KVDB Initialized!"); } public KeyValueDatabase(Context context, String dbAlias, String key) { this.pKey = key; this.pContext = context; this.dbAlias = dbAlias.endsWith(QKVConfig.KVDB_EXT) ?dbAlias: dbAlias + QKVConfig.KVDB_EXT; this.dMap = new HashMap(); this.sync(false); QKVLogger.log("i", "KVDB Initialized!"); } @Override public boolean put(K k, V v) { if (k == null || v == null) { return false; } this.dMap.put(k, v); return true; } @Override public Object get(K k) { if (k == null) { return null; } if (this.dMap.containsKey(k)) return this.dMap.get(k); else return null; } @Override public boolean containsKey(K k) { if (this.dMap.containsKey(k)) return true; else return false; } @Override public boolean containsValue(V v) { if (this.dMap.containsValue(v)) return true; else return false; } @Override public boolean remove(K k) { if (k == null) { return false; } if (this.dMap.containsKey(k)) { this.dMap.remove(k); return true; } else return false; } @Override public boolean remove(K[] k) { if (k == null || k.length == 0) { return false; } int r = 0; for (K key:k) { if (this.dMap.containsKey(key)) { this.dMap.remove(key); r++; } } if (r < k.length) return false; else return true; } @Override public void clear() { this.dMap.clear(); } @Override public int size() { return this.dMap.size(); } public List getKeys() { List list = new ArrayList(); if (this.dMap.size() > 0) { Iterator iter = dMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); list.add(key); } } return list; } public List getValues() { List list = new ArrayList(); if (this.dMap.size() > 0) { Iterator iter = dMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object value = entry.getValue(); list.add(value); } } return list; } public boolean persist() { if (this.dMap.size() > 0) { try { JSONObject treeRoot = new JSONObject(); treeRoot.put("kv_prop", new JSONObject()); JSONObject propRoot = (JSONObject) treeRoot.get("kv_prop"); propRoot.put("strc_ver", "0.8@3"); propRoot.put("enc_enabled", (this.pKey != null && this.pKey.length() > 0)); treeRoot.put("kv_data", new JSONObject()); JSONObject dataRoot = (JSONObject) treeRoot.get("kv_data"); Iterator iter = this.dMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object val = entry.getValue(); if (DataProcessor.Persistable.isValidDataType(key) && DataProcessor.Persistable.isValidDataType(val)) { if (this.pKey != null && this.pKey.length() > 0) dataRoot.put(AES256.encode(this.pKey, DataProcessor.Persistable.addPrefix(key)), AES256.encode(this.pKey, DataProcessor.Persistable.addPrefix(val))); else dataRoot.put(DataProcessor.Persistable.addPrefix(key), DataProcessor.Persistable.addPrefix(val)); } } FileOutputStream kvdbFos = pContext.openFileOutput(dbAlias == null ?QKVConfig.KVDB_FILE_NAME: dbAlias, Context.MODE_PRIVATE); kvdbFos.write(treeRoot.toString().getBytes()); kvdbFos.close(); return true; } catch (Exception e) { QKVLogger.ex(e); return false; } } else return true; } public void persist(final Callback callback) { new Thread(new Runnable(){ @Override public void run() { synchronized (dMap) { if (persist()) callback.onSuccess(); else callback.onFailed(); } } }).start(); } public boolean sync() { return this.sync(true); } public boolean sync(boolean merge) { try { if (!merge) { this.dMap.clear(); } File kvdbFile = new File(pContext.getFilesDir(), dbAlias == null ? QKVConfig.KVDB_FILE_NAME: dbAlias); String rawData = QKVFSReader.readFileBFD(kvdbFile.getAbsolutePath()); if (rawData.length() > 0) { JSONObject treeRoot = new JSONObject(rawData); if (parseKVJS((JSONObject) treeRoot.get("kv_data"))) return true; else return false; } return true; } catch (Exception e) { QKVLogger.ex(e); return false; } } public void sync(final Callback callback) { new Thread(new Runnable(){ @Override public void run() { synchronized (dMap) { if (sync()) callback.onSuccess(); else callback.onFailed(); } } }).start(); } public void sync(final boolean merge, final Callback callback) { new Thread(new Runnable(){ @Override public void run() { synchronized (dMap) { if (sync(merge)) callback.onSuccess(); else callback.onFailed(); } } }).start(); } public boolean enableEncryption(String key) { if (key != null && key.length() > 0) { this.pKey = key; persist(); return true; } else return false; } public void disableEncryption() { this.pKey = null; persist(); } private boolean parseKVJS(JSONObject json) { try { Iterator keys = json.keys(); while (keys.hasNext()) { String key = keys.next(); String val = json.get(key).toString(); Object k,v; if (this.pKey != null && this.pKey.length() > 0) { k = DataProcessor.Persistable.dePrefix(AES256.decode(this.pKey, key)); v = DataProcessor.Persistable.dePrefix(AES256.decode(this.pKey, val)); } else { k = DataProcessor.Persistable.dePrefix(key); v = DataProcessor.Persistable.dePrefix(val); } this.dMap.put(k, v); } return true; } catch (Exception e) { QKVLogger.ex(e); return false; } } public interface Callback { public void onSuccess(); public void onFailed(); } } ================================================ FILE: app/src/main/java/sumimakito/android/quickkv/database/QKVDatabase.java ================================================ /** * QucikKV * Copyright (c) 2014-2015 Sumi Makito * Licensed under Apache License 2.0. * @author sumimakito * @version 0.8.2 */ package sumimakito.android.quickkv.database; public interface QKVDatabase { boolean put(K k, V v); Object get(K k); boolean containsKey(K k); boolean containsValue(V v); boolean remove(K k); boolean remove(K[] k); void clear(); int size(); } ================================================ FILE: app/src/main/java/sumimakito/android/quickkv/security/AES256.java ================================================ /** * QucikKV * Copyright (c) 2014-2015 Sumi Makito * Licensed under Apache License 2.0. * @author sumimakito * @version 0.8.2 */ package sumimakito.android.quickkv.security; import android.util.Base64; import java.io.UnsupportedEncodingException; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import moe.feng.nhentai.BuildConfig; import sumimakito.android.quickkv.QKVConfig; public class AES256 { public static String encode(String ePasK, String eConT){ if (ePasK.length() == 0 || ePasK == null) { return ""; } if (eConT.length() == 0 || eConT == null) { return ""; } try { SecretKeySpec skeySpec = getKey(ePasK); byte[] clearText = eConT.getBytes("UTF8"); final byte[] iv = new byte[16]; Arrays.fill(iv, (byte) 0x00); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec); String encrypedValue = Base64.encodeToString(cipher.doFinal(clearText), Base64.DEFAULT); return encrypedValue; } catch (Exception e) { if (QKVConfig.DEBUG){ e.printStackTrace(); } } return ""; } public static String decode(String ePasK, String eConT){ if (ePasK.length() == 0 || ePasK == null) { return ""; } if (eConT.length() == 0 || eConT == null) { return ""; } try { SecretKey key = getKey(ePasK); final byte[] iv = new byte[16]; Arrays.fill(iv, (byte) 0x00); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); byte[] encrypedPwdBytes = Base64.decode(eConT, Base64.DEFAULT); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec); byte[] decrypedValueBytes = (cipher.doFinal(encrypedPwdBytes)); String decrypedValue = new String(decrypedValueBytes); return decrypedValue; } catch (Exception e) { if (BuildConfig.DEBUG){ e.printStackTrace(); } } return ""; } private static SecretKeySpec getKey(String password) throws UnsupportedEncodingException { int keyLength = 256; byte[] keyBytes = new byte[keyLength / 8]; Arrays.fill(keyBytes, (byte) 0x0); byte[] passwordBytes = password.getBytes("UTF-8"); int length = passwordBytes.length < keyBytes.length ? passwordBytes.length : keyBytes.length; System.arraycopy(passwordBytes, 0, keyBytes, 0, length); SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); return key; } } ================================================ FILE: app/src/main/res/color/drawer_item_color.xml ================================================ ================================================ FILE: app/src/main/res/drawable/shadow_gradient.xml ================================================ ================================================ FILE: app/src/main/res/drawable/shadow_gradient_reserve.xml ================================================ ================================================ FILE: app/src/main/res/drawable/shadow_normal.xml ================================================ ================================================ FILE: app/src/main/res/drawable/shadow_normal_reserve.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_book_details.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_gallery.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_main.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_search_result.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_settings.xml ================================================ ================================================ FILE: app/src/main/res/layout/custom_preference.xml ================================================ ================================================ FILE: app/src/main/res/layout/custom_preference_widget_switch.xml ================================================ ================================================ FILE: app/src/main/res/layout/fragment_book_page.xml ================================================ ================================================ FILE: app/src/main/res/layout/fragment_download.xml ================================================ ================================================ FILE: app/src/main/res/layout/fragment_favorite.xml ================================================ ================================================ FILE: app/src/main/res/layout/fragment_home.xml ================================================ ================================================ FILE: app/src/main/res/layout/list_item_book_card.xml ================================================ ================================================ FILE: app/src/main/res/layout/list_item_book_picture_thumb.xml ================================================ ================================================ FILE: app/src/main/res/layout/list_item_menu_row.xml ================================================ ================================================ FILE: app/src/main/res/layout/navigation_header.xml ================================================ ================================================ FILE: app/src/main/res/menu/menu_main.xml ================================================ ================================================ FILE: app/src/main/res/menu/navigation_menu.xml ================================================ ================================================ FILE: app/src/main/res/values/attrs.xml ================================================ ================================================ FILE: app/src/main/res/values/color.xml ================================================ #9575CD #673AB7 #4527A0 #BA68C8 #E91E63 #3F51B5 #2196F3 #009688 #4CAF50 #81C784 #FF9800 #795548 #4F000000 ================================================ FILE: app/src/main/res/values/dimen.xml ================================================ 5dp 256dp 320dp 2dp 4dp 14sp 72sp ================================================ FILE: app/src/main/res/values/strings.xml ================================================ NHBooks Settings Search Home Tags Characters Latest Saved books Favorites @string/title_page_latest @string/title_page_download @string/title_page_favorite Failed to connect to NHentai. Try again Details Tags: Parodies: Language: Characters: Artists: Groups: Uploaded time: Gallery Search result Search result: %s No result. Settings About Application version Licenses Sina Weibo \@某燒餅 Google Plus +Fung Jichun Github Repo "https://github.com/fython/NHentai-android" ================================================ FILE: app/src/main/res/values/styles.xml ================================================ ================================================ FILE: app/src/main/res/values-v21/styles.xml ================================================ ================================================ FILE: app/src/main/res/values-zh-rCN/strings.xml ================================================ NH 本子 设置 搜索 主页 标签 人物 最新 已保存的本子 我的收藏 @string/title_page_latest @string/title_page_download @string/title_page_favorite 无法连接到 NHentai。 重试 详情 标签: 作品: 语言: 人物: 画家: 组别: 上传时间: 图库 搜索结果 搜索结果: %s 没有结果。 设置 关于 应用程序版本 开源项目许可协议 新浪微博 \@某燒餅 Google+ +Fung Jichun Github 开源项目 "https://github.com/fython/NHentai-android" ================================================ FILE: app/src/main/res/values-zh-rTW/strings.xml ================================================ NH 本子 設置 搜尋 主頁 標籤 角色 最新 已儲存的本子 我的最愛 @string/title_page_latest @string/title_page_download @string/title_page_favorite 無法連接到 NHentai。 重試 詳情 標籤: 作品: 語言: 角色: 畫家: 組別: 上載時間: 畫廊 搜尋結果 搜尋結果: %s 沒有結果。 設置 關於 應用程式版本 開源項目許可協議 新浪微博 \@某燒餅 Google+ +Fung Jichun Github 開源項目 "https://github.com/fython/NHentai-android" ================================================ FILE: app/src/main/res/xml/settings_main.xml ================================================ ================================================ FILE: build.gradle ================================================ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.1.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() } } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Wed May 27 13:24:38 CST 2015 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-2.2-all.zip ================================================ FILE: gradle.properties ================================================ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx10248m -XX:MaxPermSize=256m # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true ================================================ FILE: gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # For Cygwin, ensure paths are in UNIX format before anything is touched. if $cygwin ; then [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` fi # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >&- APP_HOME="`pwd -P`" cd "$SAVED" >&- CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: libraries/PersistentSearch/.gitignore ================================================ /build ================================================ FILE: libraries/PersistentSearch/build.gradle ================================================ apply plugin: 'com.android.library' android { compileSdkVersion 22 buildToolsVersion "22.0.1" defaultConfig { minSdkVersion 11 targetSdkVersion 22 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } lintOptions { abortOnError false } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.nineoldandroids:library:2.4.0+' compile 'com.android.support:appcompat-v7:22.2.0' } ================================================ FILE: libraries/PersistentSearch/gradle.properties ================================================ POM_NAME=Persistent Search POM_ARTIFACT_ID=library POM_PACKAGING=aar ================================================ FILE: libraries/PersistentSearch/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in C:/Users/Kieron/Android/adt-bundle-windows-x86_64-20140702/adt-bundle-windows-x86_64-20140702/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: libraries/PersistentSearch/src/main/AndroidManifest.xml ================================================ ================================================ FILE: libraries/PersistentSearch/src/main/java/com/balysv/materialmenu/MaterialMenu.java ================================================ /* * Copyright (C) 2014 Balys Valentukevicius * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.balysv.materialmenu; import android.view.animation.Interpolator; import com.nineoldandroids.animation.Animator; import static com.balysv.materialmenu.MaterialMenuDrawable.IconState; /** * API for interaction with {@link MaterialMenuDrawable} */ public interface MaterialMenu { /** * Change icon without animation * * @param state new icon state */ public void setState(IconState state); /** * Return current icon state * * @return icon state */ public IconState getState(); /** * Animate icon to given state. * * @param state new icon state */ public void animateState(IconState state); /** * Animate icon to given state and draw touch circle * * @param state new icon state */ public void animatePressedState(IconState state); /** * Set color of icon * * @param color new icon color */ public void setColor(int color); /** * Set duration of transformation animations * * @param duration new animation duration */ public void setTransformationDuration(int duration); /** * Set duration of pressed state circle animation * * @param duration new animation duration */ public void setPressedDuration(int duration); /** * Set interpolator for transformation animations * * @param interpolator new interpolator */ public void setInterpolator(Interpolator interpolator); /** * Set listener for {@code MaterialMenuDrawable} animation events * * @param listener new listener or null to remove any listener */ public void setAnimationListener(Animator.AnimatorListener listener); /** * Enable RTL layout. Flips all icons horizontally * * @param rtlEnabled true to enable RTL layout */ public void setRTLEnabled(boolean rtlEnabled); /** * Manually set a transformation value for an {@link com.balysv.materialmenu.MaterialMenuDrawable.AnimationState} * * @param animationState state to set value in * @param value between {@link com.balysv.materialmenu.MaterialMenuDrawable#TRANSFORMATION_START} and * {@link com.balysv.materialmenu.MaterialMenuDrawable#TRANSFORMATION_END}. */ public void setTransformationOffset(MaterialMenuDrawable.AnimationState animationState, float value); /** * @return {@link MaterialMenuDrawable} to be used for the menu */ public MaterialMenuDrawable getDrawable(); } ================================================ FILE: libraries/PersistentSearch/src/main/java/com/balysv/materialmenu/MaterialMenuDrawable.java ================================================ /* * Copyright (C) 2014 Balys Valentukevicius * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.balysv.materialmenu; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.util.TypedValue; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import com.nineoldandroids.animation.ObjectAnimator; import com.nineoldandroids.util.Property; import static android.graphics.Paint.Style; import static com.nineoldandroids.animation.Animator.AnimatorListener; public class MaterialMenuDrawable extends Drawable implements Animatable { public enum IconState { BURGER, ARROW, X, CHECK } public enum AnimationState { BURGER_ARROW, BURGER_X, ARROW_X, ARROW_CHECK, BURGER_CHECK, X_CHECK; public IconState getFirstState() { switch (this) { case BURGER_ARROW: return IconState.BURGER; case BURGER_X: return IconState.BURGER; case ARROW_X: return IconState.ARROW; case ARROW_CHECK: return IconState.ARROW; case BURGER_CHECK: return IconState.BURGER; case X_CHECK: return IconState.X; default: return null; } } public IconState getSecondState() { switch (this) { case BURGER_ARROW: return IconState.ARROW; case BURGER_X: return IconState.X; case ARROW_X: return IconState.X; case ARROW_CHECK: return IconState.CHECK; case BURGER_CHECK: return IconState.CHECK; case X_CHECK: return IconState.CHECK; default: return null; } } } public enum Stroke { /** * 3 dip */ REGULAR(3), /** * 2 dip */ THIN(2), /** * 1 dip */ EXTRA_THIN(1); private final int strokeWidth; Stroke(int strokeWidth) { this.strokeWidth = strokeWidth; } protected static Stroke valueOf(int strokeWidth) { switch (strokeWidth) { case 3: return REGULAR; case 2: return THIN; case 1: return EXTRA_THIN; default: return THIN; } } } public static final int DEFAULT_COLOR = Color.WHITE; public static final int DEFAULT_SCALE = 1; public static final int DEFAULT_TRANSFORM_DURATION = 800; public static final int DEFAULT_PRESSED_DURATION = 400; private static final int BASE_DRAWABLE_WIDTH = 40; private static final int BASE_DRAWABLE_HEIGHT = 40; private static final int BASE_ICON_WIDTH = 20; private static final int BASE_CIRCLE_RADIUS = 18; private static final float ARROW_MID_LINE_ANGLE = 180; private static final float ARROW_TOP_LINE_ANGLE = 135; private static final float ARROW_BOT_LINE_ANGLE = 225; private static final float X_TOP_LINE_ANGLE = 44; private static final float X_BOT_LINE_ANGLE = -44; private static final float X_ROTATION_ANGLE = 90; private static final float CHECK_MIDDLE_ANGLE = 135; private static final float CHECK_BOTTOM_ANGLE = -90; private static final float TRANSFORMATION_START = 0; private static final float TRANSFORMATION_MID = 1.0f; private static final float TRANSFORMATION_END = 2.0f; private static final int DEFAULT_CIRCLE_ALPHA = 200; private final float diph; private final float dip1; private final float dip2; private final float dip3; private final float dip4; private final float dip6; private final float dip8; private final int width; private final int height; private final float strokeWidth; private final float iconWidth; private final float topPadding; private final float sidePadding; private final float circleRadius; private final Stroke stroke; private final Object lock = new Object(); private final Paint iconPaint = new Paint(); private final Paint circlePaint = new Paint(); private float transformationValue = 0f; private float pressedProgressValue = 0f; private boolean transformationRunning = false; private IconState currentIconState = IconState.BURGER; private AnimationState animationState = AnimationState.BURGER_ARROW; private IconState animatingIconState; private boolean drawTouchCircle; private boolean neverDrawTouch; private boolean rtlEnabled; private ObjectAnimator transformation; private ObjectAnimator pressedCircle; private AnimatorListener animatorListener; private MaterialMenuState materialMenuState; public MaterialMenuDrawable(Context context, int color, Stroke stroke) { this(context, color, stroke, DEFAULT_SCALE, DEFAULT_TRANSFORM_DURATION, DEFAULT_PRESSED_DURATION); } public MaterialMenuDrawable(Context context, int color, Stroke stroke, int transformDuration, int pressedDuration) { this(context, color, stroke, DEFAULT_SCALE, transformDuration, pressedDuration); } public MaterialMenuDrawable(Context context, int color, Stroke stroke, int scale, int transformDuration, int pressedDuration) { Resources resources = context.getResources(); // convert each separately due to various densities this.dip1 = dpToPx(resources, 1) * scale; this.dip2 = dpToPx(resources, 2) * scale; this.dip3 = dpToPx(resources, 3) * scale; this.dip4 = dpToPx(resources, 4) * scale; this.dip6 = dpToPx(resources, 6) * scale; this.dip8 = dpToPx(resources, 8) * scale; this.diph = dip1 / 2; this.stroke = stroke; this.width = (int) (dpToPx(resources, BASE_DRAWABLE_WIDTH) * scale); this.height = (int) (dpToPx(resources, BASE_DRAWABLE_HEIGHT) * scale); this.iconWidth = dpToPx(resources, BASE_ICON_WIDTH) * scale; this.circleRadius = dpToPx(resources, BASE_CIRCLE_RADIUS) * scale; this.strokeWidth = dpToPx(resources, stroke.strokeWidth) * scale; this.sidePadding = (width - iconWidth) / 2; this.topPadding = (height - 5 * dip3) / 2; initPaint(color); initAnimations(transformDuration, pressedDuration); materialMenuState = new MaterialMenuState(); } private MaterialMenuDrawable(int color, Stroke stroke, long transformDuration, long pressedDuration, int width, int height, float iconWidth, float circleRadius, float strokeWidth, float dip1 ) { this.dip1 = dip1; this.dip2 = dip1 * 2; this.dip3 = dip1 * 3; this.dip4 = dip1 * 4; this.dip6 = dip1 * 6; this.dip8 = dip1 * 8; this.diph = dip1 / 2; this.stroke = stroke; this.width = width; this.height = height; this.iconWidth = iconWidth; this.circleRadius = circleRadius; this.strokeWidth = strokeWidth; this.sidePadding = (width - iconWidth) / 2; this.topPadding = (height - 5 * dip3) / 2; initPaint(color); initAnimations((int) transformDuration, (int) pressedDuration); materialMenuState = new MaterialMenuState(); } private void initPaint(int color) { iconPaint.setAntiAlias(true); iconPaint.setStyle(Style.STROKE); iconPaint.setStrokeWidth(strokeWidth); iconPaint.setColor(color); circlePaint.setAntiAlias(true); circlePaint.setStyle(Style.FILL); circlePaint.setColor(color); circlePaint.setAlpha(DEFAULT_CIRCLE_ALPHA); setBounds(0, 0, width, height); } /* * Drawing */ @Override public void draw(Canvas canvas) { final float ratio = transformationValue <= 1 ? transformationValue : 2 - transformationValue; if (rtlEnabled) { canvas.save(); canvas.scale(-1, 1, 0, 0); canvas.translate(-getIntrinsicWidth(), 0); } drawTopLine(canvas, ratio); drawMiddleLine(canvas, ratio); drawBottomLine(canvas, ratio); if (rtlEnabled) { canvas.restore(); } if (drawTouchCircle) drawTouchCircle(canvas); } private void drawTouchCircle(Canvas canvas) { canvas.restore(); canvas.drawCircle(width / 2, height / 2, pressedProgressValue, circlePaint); } private void drawMiddleLine(Canvas canvas, float ratio) { canvas.restore(); canvas.save(); float rotation = 0; float pivotX = width / 2; float pivotY = width / 2; float startX = sidePadding; float startY = topPadding + dip3 / 2 * 5; float stopX = width - sidePadding; float stopY = topPadding + dip3 / 2 * 5; int alpha = 255; switch (animationState) { case BURGER_ARROW: // rotate by 180 if (isMorphingForward()) { rotation = ratio * ARROW_MID_LINE_ANGLE; } else { rotation = ARROW_MID_LINE_ANGLE + (1 - ratio) * ARROW_MID_LINE_ANGLE; } // shorten one end stopX -= ratio * resolveStrokeModifier(ratio) / 2; break; case BURGER_X: // fade out alpha = (int) ((1 - ratio) * 255); break; case ARROW_X: // fade out and shorten one end alpha = (int) ((1 - ratio) * 255); startX += (1 - ratio) * dip2; break; case ARROW_CHECK: if (isMorphingForward()) { // rotate until required angle rotation = ratio * CHECK_MIDDLE_ANGLE; } else { // rotate back to starting angle rotation = CHECK_MIDDLE_ANGLE - CHECK_MIDDLE_ANGLE * (1 - ratio); } // shorten one end and lengthen the other startX += dip3 / 2 + dip4 - (1 - ratio) * dip2; stopX += ratio * dip1; pivotX = width / 2 + dip3 + diph; break; case BURGER_CHECK: // rotate until required angle rotation = ratio * CHECK_MIDDLE_ANGLE; // lengthen both ends startX += ratio * (dip4 + dip3 / 2); stopX += ratio * dip1; pivotX = width / 2 + dip3 + diph; break; case X_CHECK: // fade in alpha = (int) (ratio * 255); // rotation to check angle rotation = ratio * CHECK_MIDDLE_ANGLE; // lengthen both ends startX += ratio * (dip4 + dip3 / 2); stopX += ratio * dip1; pivotX = width / 2 + dip3 + diph; break; } iconPaint.setAlpha(alpha); canvas.rotate(rotation, pivotX, pivotY); canvas.drawLine(startX, startY, stopX, stopY, iconPaint); iconPaint.setAlpha(255); } private void drawTopLine(Canvas canvas, float ratio) { canvas.save(); float rotation = 0, pivotX = 0, pivotY = 0; float rotation2 = 0; // pivot at center of line float pivotX2 = width / 2 + dip3 / 2; float pivotY2 = topPadding + dip2; float startX = sidePadding; float startY = topPadding + dip2; float stopX = width - sidePadding; float stopY = topPadding + dip2; int alpha = 255; switch (animationState) { case BURGER_ARROW: if (isMorphingForward()) { // rotate until required angle rotation = ratio * ARROW_BOT_LINE_ANGLE; } else { // rotate back to start doing a 360 rotation = ARROW_BOT_LINE_ANGLE + (1 - ratio) * ARROW_TOP_LINE_ANGLE; } // rotate by middle pivotX = width / 2; pivotY = height / 2; // shorten both ends stopX -= resolveStrokeModifier(ratio); startX += dip3 * ratio; break; case BURGER_X: // rotate until required angles rotation = X_TOP_LINE_ANGLE * ratio; rotation2 = X_ROTATION_ANGLE * ratio; // pivot at left corner of line pivotX = sidePadding + dip4; pivotY = topPadding + dip3; // shorten one end startX += dip3 * ratio; break; case ARROW_X: // rotate from ARROW angle to X angle rotation = ARROW_BOT_LINE_ANGLE + (X_TOP_LINE_ANGLE - ARROW_BOT_LINE_ANGLE) * ratio; rotation2 = X_ROTATION_ANGLE * ratio; // move pivot from ARROW pivot to X pivot pivotX = width / 2 + (sidePadding + dip4 - width / 2) * ratio; pivotY = height / 2 + (topPadding + dip3 - height / 2) * ratio; // lengthen both ends stopX -= resolveStrokeModifier(ratio); startX += dip3; break; case ARROW_CHECK: // fade out alpha = (int) ((1 - ratio) * 255); // retain starting arrow configuration rotation = ARROW_BOT_LINE_ANGLE; pivotX = width / 2; pivotY = height / 2; // shorted both ends stopX -= resolveStrokeModifier(1); startX += dip3; break; case BURGER_CHECK: // fade out alpha = (int) ((1 - ratio) * 255); break; case X_CHECK: // retain X configuration rotation = X_TOP_LINE_ANGLE; rotation2 = X_ROTATION_ANGLE; pivotX = sidePadding + dip4; pivotY = topPadding + dip3; stopX += dip3 - dip3 * (1 - ratio); startX += dip3; // fade out alpha = (int) ((1 - ratio) * 255); break; } iconPaint.setAlpha(alpha); canvas.rotate(rotation, pivotX, pivotY); canvas.rotate(rotation2, pivotX2, pivotY2); canvas.drawLine(startX, startY, stopX, stopY, iconPaint); iconPaint.setAlpha(255); } private void drawBottomLine(Canvas canvas, float ratio) { canvas.restore(); canvas.save(); float rotation = 0, pivotX = 0, pivotY = 0; float rotation2 = 0; // pivot at center of line float pivotX2 = width / 2 + dip3 / 2; float pivotY2 = height - topPadding - dip2; float startX = sidePadding; float startY = height - topPadding - dip2; float stopX = width - sidePadding; float stopY = height - topPadding - dip2; switch (animationState) { case BURGER_ARROW: if (isMorphingForward()) { // rotate to required angle rotation = ARROW_TOP_LINE_ANGLE * ratio; } else { // rotate back to start doing a 360 rotation = ARROW_TOP_LINE_ANGLE + (1 - ratio) * ARROW_BOT_LINE_ANGLE; } // pivot center of canvas pivotX = width / 2; pivotY = height / 2; // shorten both ends stopX = width - sidePadding - resolveStrokeModifier(ratio); startX = sidePadding + dip3 * ratio; break; case BURGER_X: if (isMorphingForward()) { // rotate around rotation2 = -X_ROTATION_ANGLE * ratio; } else { // rotate directly rotation2 = X_ROTATION_ANGLE * ratio; } // rotate to required angle rotation = X_BOT_LINE_ANGLE * ratio; // pivot left corner of line pivotX = sidePadding + dip4; pivotY = height - topPadding - dip3; // shorten one end startX += dip3 * ratio; break; case ARROW_X: // rotate from ARROW angle to X angle rotation = ARROW_TOP_LINE_ANGLE + (360 + X_BOT_LINE_ANGLE - ARROW_TOP_LINE_ANGLE) * ratio; rotation2 = -X_ROTATION_ANGLE * ratio; // move pivot from ARROW pivot to X pivot pivotX = width / 2 + (sidePadding + dip4 - width / 2) * ratio; pivotY = height / 2 + (height / 2 - topPadding - dip3) * ratio; // lengthen both ends stopX -= resolveStrokeModifier(ratio); startX += dip3; break; case ARROW_CHECK: // rotate from ARROW angle to CHECK angle rotation = ARROW_TOP_LINE_ANGLE + ratio * CHECK_BOTTOM_ANGLE; // move pivot from ARROW pivot to CHECK pivot pivotX = width / 2 + dip3 * ratio; pivotY = height / 2 - dip3 * ratio; // length stays same as ARROW stopX -= resolveStrokeModifier(1); startX += dip3 + (dip4 + dip1) * ratio; break; case BURGER_CHECK: // rotate from ARROW angle to CHECK angle rotation = ratio * (CHECK_BOTTOM_ANGLE + ARROW_TOP_LINE_ANGLE); // move pivot from BURGER pivot to CHECK pivot pivotX = width / 2 + dip3 * ratio; pivotY = height / 2 - dip3 * ratio; // length stays same as BURGER startX += dip8 * ratio; stopX -= resolveStrokeModifier(ratio); break; case X_CHECK: // rotate from X to CHECK angles rotation2 = -X_ROTATION_ANGLE * (1 - ratio); rotation = X_BOT_LINE_ANGLE + (CHECK_BOTTOM_ANGLE + ARROW_TOP_LINE_ANGLE - X_BOT_LINE_ANGLE) * ratio; // move pivot from X to CHECK pivotX = sidePadding + dip4 + (width / 2 + dip3 - sidePadding - dip4) * ratio; pivotY = height - topPadding - dip3 + (topPadding + height / 2 - height) * ratio; // shorten both ends startX += dip8 - (dip4 + dip1) * (1 - ratio); stopX -= resolveStrokeModifier(1 - ratio); break; } canvas.rotate(rotation, pivotX, pivotY); canvas.rotate(rotation2, pivotX2, pivotY2); canvas.drawLine(startX, startY, stopX, stopY, iconPaint); } private boolean isMorphingForward() { return transformationValue <= TRANSFORMATION_MID; } private float resolveStrokeModifier(float ratio) { switch (stroke) { case REGULAR: if (animationState == AnimationState.ARROW_X || animationState == AnimationState.X_CHECK) { return dip3 - (dip3 * ratio); } return ratio * dip3; case THIN: if (animationState == AnimationState.ARROW_X || animationState == AnimationState.X_CHECK) { return dip3 + diph - (dip3 + diph) * ratio; } return ratio * (dip3 + diph); case EXTRA_THIN: if (animationState == AnimationState.ARROW_X || animationState == AnimationState.X_CHECK) { return dip4 - ((dip3 + dip1) * ratio); } return ratio * dip4; } return 0; } @Override public void setAlpha(int alpha) { iconPaint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter cf) { iconPaint.setColorFilter(cf); } @Override public int getOpacity() { return PixelFormat.TRANSPARENT; } /* * Accessor methods */ public void setColor(int color) { iconPaint.setColor(color); circlePaint.setColor(color); invalidateSelf(); } public void setTransformationDuration(int duration) { transformation.setDuration(duration); } public void setPressedDuration(int duration) { pressedCircle.setDuration(duration); } public void setInterpolator(Interpolator interpolator) { transformation.setInterpolator(interpolator); } public void setAnimationListener(AnimatorListener listener) { if (animatorListener != null) { transformation.removeListener(animatorListener); } if (listener != null) { transformation.addListener(listener); } animatorListener = listener; } public void setNeverDrawTouch(boolean neverDrawTouch) { this.neverDrawTouch = neverDrawTouch; } public void setIconState(IconState iconState) { synchronized (lock) { if (transformationRunning) { transformation.cancel(); transformationRunning = false; } if (currentIconState == iconState) return; switch (iconState) { case BURGER: animationState = AnimationState.BURGER_ARROW; transformationValue = TRANSFORMATION_START; break; case ARROW: animationState = AnimationState.BURGER_ARROW; transformationValue = TRANSFORMATION_MID; break; case X: animationState = AnimationState.BURGER_X; transformationValue = TRANSFORMATION_MID; break; case CHECK: animationState = AnimationState.BURGER_CHECK; transformationValue = TRANSFORMATION_MID; } currentIconState = iconState; invalidateSelf(); } } public void animateIconState(IconState state, boolean drawTouch) { synchronized (lock) { if (transformationRunning) { transformation.end(); pressedCircle.end(); } drawTouchCircle = drawTouch; animatingIconState = state; start(); } } public IconState setTransformationOffset(AnimationState animationState, float offset) { if (offset < TRANSFORMATION_START || offset > TRANSFORMATION_END) { throw new IllegalArgumentException( String.format("Value must be between %s and %s", TRANSFORMATION_START, TRANSFORMATION_END) ); } this.animationState = animationState; final boolean isFirstIcon = offset < TRANSFORMATION_MID || offset == TRANSFORMATION_END; currentIconState = isFirstIcon ? animationState.getFirstState() : animationState.getSecondState(); animatingIconState = isFirstIcon ? animationState.getSecondState() : animationState.getFirstState(); setTransformationValue(offset); return currentIconState; } public void setRTLEnabled(boolean rtlEnabled) { this.rtlEnabled = rtlEnabled; invalidateSelf(); } public IconState getIconState() { return currentIconState; } /* * Animations */ private Property transformationProperty = new Property(Float.class, "transformation") { @Override public Float get(MaterialMenuDrawable object) { return object.getTransformationValue(); } @Override public void set(MaterialMenuDrawable object, Float value) { object.setTransformationValue(value); } }; private Property pressedProgressProperty = new Property(Float.class, "pressedProgress") { @Override public Float get(MaterialMenuDrawable object) { return object.getPressedProgress(); } @Override public void set(MaterialMenuDrawable object, Float value) { object.setPressedProgress(value); } }; public Float getTransformationValue() { return transformationValue; } public void setTransformationValue(Float value) { this.transformationValue = value; invalidateSelf(); } public Float getPressedProgress() { return pressedProgressValue; } public void setPressedProgress(Float value) { this.pressedProgressValue = value; circlePaint.setAlpha((int) (DEFAULT_CIRCLE_ALPHA * (1 - value / (circleRadius * 1.22f)))); invalidateSelf(); } private void initAnimations(int transformDuration, int pressedDuration) { transformation = ObjectAnimator.ofFloat(this, transformationProperty, 0); transformation.setInterpolator(new DecelerateInterpolator(3)); transformation.setDuration(transformDuration); transformation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { transformationRunning = false; setIconState(animatingIconState); } }); pressedCircle = ObjectAnimator.ofFloat(this, pressedProgressProperty, 0, 0); pressedCircle.setDuration(pressedDuration); pressedCircle.setInterpolator(new DecelerateInterpolator()); pressedCircle.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { pressedProgressValue = 0; } @Override public void onAnimationCancel(Animator animation) { pressedProgressValue = 0; } }); } private boolean resolveTransformation() { boolean isCurrentBurger = currentIconState == IconState.BURGER; boolean isCurrentArrow = currentIconState == IconState.ARROW; boolean isCurrentX = currentIconState == IconState.X; boolean isCurrentCheck = currentIconState == IconState.CHECK; boolean isAnimatingBurger = animatingIconState == IconState.BURGER; boolean isAnimatingArrow = animatingIconState == IconState.ARROW; boolean isAnimatingX = animatingIconState == IconState.X; boolean isAnimatingCheck = animatingIconState == IconState.CHECK; if ((isCurrentBurger && isAnimatingArrow) || (isCurrentArrow && isAnimatingBurger)) { animationState = AnimationState.BURGER_ARROW; return isCurrentBurger; } if ((isCurrentArrow && isAnimatingX) || (isCurrentX && isAnimatingArrow)) { animationState = AnimationState.ARROW_X; return isCurrentArrow; } if ((isCurrentBurger && isAnimatingX) || (isCurrentX && isAnimatingBurger)) { animationState = AnimationState.BURGER_X; return isCurrentBurger; } if ((isCurrentArrow && isAnimatingCheck) || (isCurrentCheck && isAnimatingArrow)) { animationState = AnimationState.ARROW_CHECK; return isCurrentArrow; } if ((isCurrentBurger && isAnimatingCheck) || (isCurrentCheck && isAnimatingBurger)) { animationState = AnimationState.BURGER_CHECK; return isCurrentBurger; } if ((isCurrentX && isAnimatingCheck) || (isCurrentCheck && isAnimatingX)) { animationState = AnimationState.X_CHECK; return isCurrentX; } throw new IllegalStateException( String.format("Animating from %s to %s is not supported", currentIconState, animatingIconState) ); } @Override public void start() { if (transformationRunning) return; if (animatingIconState != null && animatingIconState != currentIconState) { transformationRunning = true; final boolean direction = resolveTransformation(); transformation.setFloatValues( direction ? TRANSFORMATION_START : TRANSFORMATION_MID, direction ? TRANSFORMATION_MID : TRANSFORMATION_END ); transformation.start(); } if (pressedCircle.isRunning()) { pressedCircle.cancel(); } if (drawTouchCircle && !neverDrawTouch) { pressedCircle.setFloatValues(0, circleRadius * 1.22f); pressedCircle.start(); } invalidateSelf(); } @Override public void stop() { if (isRunning() && transformation.isRunning()) { transformation.end(); } else { transformationRunning = false; invalidateSelf(); } } @Override public boolean isRunning() { return transformationRunning; } @Override public int getIntrinsicWidth() { return width; } @Override public int getIntrinsicHeight() { return height; } @Override public ConstantState getConstantState() { materialMenuState.changingConfigurations = getChangingConfigurations(); return materialMenuState; } @Override public Drawable mutate() { materialMenuState = new MaterialMenuState(); return this; } private final class MaterialMenuState extends ConstantState { private int changingConfigurations; private MaterialMenuState() { } @Override public Drawable newDrawable() { MaterialMenuDrawable drawable = new MaterialMenuDrawable( circlePaint.getColor(), stroke, transformation.getDuration(), pressedCircle.getDuration(), width, height, iconWidth, circleRadius, strokeWidth, dip1 ); drawable.setIconState(animatingIconState != null ? animatingIconState : currentIconState); drawable.setRTLEnabled(rtlEnabled); return drawable; } @Override public int getChangingConfigurations() { return changingConfigurations; } } static float dpToPx(Resources resources, float dp) { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.getDisplayMetrics()); } } ================================================ FILE: libraries/PersistentSearch/src/main/java/com/balysv/materialmenu/MaterialMenuView.java ================================================ /* * Copyright (C) 2014 Balys Valentukevicius * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.balysv.materialmenu; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.view.View; import android.view.animation.Interpolator; import com.nineoldandroids.animation.Animator; import com.quinny898.library.persistentsearch.R; import static com.balysv.materialmenu.MaterialMenuDrawable.DEFAULT_COLOR; import static com.balysv.materialmenu.MaterialMenuDrawable.DEFAULT_PRESSED_DURATION; import static com.balysv.materialmenu.MaterialMenuDrawable.DEFAULT_SCALE; import static com.balysv.materialmenu.MaterialMenuDrawable.DEFAULT_TRANSFORM_DURATION; import static com.balysv.materialmenu.MaterialMenuDrawable.IconState; import static com.balysv.materialmenu.MaterialMenuDrawable.Stroke; /** * A basic View wrapper of {@link com.balysv.materialmenu.MaterialMenuDrawable}. Used * for custom view ActionBar or other layouts */ public class MaterialMenuView extends View implements MaterialMenu { private MaterialMenuDrawable drawable; private IconState currentState = IconState.BURGER; public MaterialMenuView(Context context) { this(context, null); } public MaterialMenuView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MaterialMenuView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attributeSet) { TypedArray attr = getTypedArray(context, attributeSet, R.styleable.MaterialMenuView); try { int color = attr.getColor(R.styleable.MaterialMenuView_mm_color, DEFAULT_COLOR); int scale = attr.getInteger(R.styleable.MaterialMenuView_mm_scale, DEFAULT_SCALE); int transformDuration = attr.getInteger(R.styleable.MaterialMenuView_mm_transformDuration, DEFAULT_TRANSFORM_DURATION); int pressedDuration = attr.getInteger(R.styleable.MaterialMenuView_mm_pressedDuration, DEFAULT_PRESSED_DURATION); Stroke stroke = Stroke.valueOf(attr.getInteger(R.styleable.MaterialMenuView_mm_strokeWidth, 0)); boolean rtlEnabled = attr.getBoolean(R.styleable.MaterialMenuView_mm_rtlEnabled, false); drawable = new MaterialMenuDrawable(context, color, stroke, scale, transformDuration, pressedDuration); drawable.setRTLEnabled(rtlEnabled); } finally { attr.recycle(); } drawable.setCallback(this); } @Override public void draw(Canvas canvas) { super.draw(canvas); if (getPaddingLeft() != 0 || getPaddingTop() != 0) { int saveCount = canvas.getSaveCount(); canvas.save(); canvas.translate(getPaddingLeft(), getPaddingTop()); drawable.draw(canvas); canvas.restoreToCount(saveCount); } else { drawable.draw(canvas); } } @Override public void setPadding(int left, int top, int right, int bottom) { super.setPadding(left, top, right, bottom); adjustDrawablePadding(); } @Override protected boolean verifyDrawable(Drawable who) { return who == drawable || super.verifyDrawable(who); } @Override public void setState(IconState state) { currentState = state; drawable.setIconState(state); } @Override public IconState getState() { return drawable.getIconState(); } @Override public void animateState(IconState state) { currentState = state; drawable.animateIconState(state, false); } @Override public void animatePressedState(IconState state) { currentState = state; drawable.animateIconState(state, true); } @Override public void setColor(int color) { drawable.setColor(color); } @Override public void setTransformationDuration(int duration) { drawable.setTransformationDuration(duration); } @Override public void setPressedDuration(int duration) { drawable.setPressedDuration(duration); } @Override public void setInterpolator(Interpolator interpolator) { drawable.setInterpolator(interpolator); } @Override public void setAnimationListener(Animator.AnimatorListener listener) { drawable.setAnimationListener(listener); } @Override public void setRTLEnabled(boolean rtlEnabled) { drawable.setRTLEnabled(rtlEnabled); } @Override public void setTransformationOffset(MaterialMenuDrawable.AnimationState animationState, float value) { currentState = drawable.setTransformationOffset(animationState, value); } @Override public MaterialMenuDrawable getDrawable() { return drawable; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int paddingX = getPaddingLeft() + getPaddingRight(); int paddingY = getPaddingTop() + getPaddingBottom(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { widthMeasureSpec = MeasureSpec.makeMeasureSpec(drawable.getIntrinsicWidth() + paddingX, MeasureSpec.EXACTLY); heightMeasureSpec = MeasureSpec.makeMeasureSpec(drawable.getIntrinsicHeight() + paddingY, MeasureSpec.EXACTLY); setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); } else { setMeasuredDimension(drawable.getIntrinsicWidth() + paddingX, drawable.getIntrinsicHeight() + paddingY); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); adjustDrawablePadding(); } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState savedState = new SavedState(superState); savedState.state = currentState; return savedState; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); setState(savedState.state); } private void adjustDrawablePadding() { if (drawable != null) { drawable.setBounds( 0, 0, drawable.getIntrinsicWidth() + getPaddingLeft() + getPaddingRight(), drawable.getIntrinsicHeight() + getPaddingTop() + getPaddingBottom() ); } } private TypedArray getTypedArray(Context context, AttributeSet attributeSet, int[] attr) { return context.obtainStyledAttributes(attributeSet, attr, 0, 0); } private static class SavedState extends BaseSavedState { protected IconState state; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); state = IconState.valueOf(in.readString()); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeString(state.name()); } public static final Creator CREATOR = new Creator() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } } ================================================ FILE: libraries/PersistentSearch/src/main/java/com/quinny898/library/persistentsearch/SearchBox.java ================================================ package com.quinny898.library.persistentsearch; import android.animation.LayoutTransition; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.os.Build; import android.speech.RecognizerIntent; import android.text.Editable; import android.text.InputFilter; import android.text.TextUtils; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Display; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import com.balysv.materialmenu.MaterialMenuDrawable.IconState; import com.balysv.materialmenu.MaterialMenuView; import java.util.ArrayList; import java.util.List; import io.codetail.animation.ReverseInterpolator; import io.codetail.animation.SupportAnimator; import io.codetail.animation.ViewAnimationUtils; public class SearchBox extends RelativeLayout { public static final int VOICE_RECOGNITION_CODE = 1234; private MaterialMenuView materialMenu; private TextView logo; private EditText search; private Context context; private ListView results; private ArrayList resultList; private ArrayList searchables; private boolean searchOpen; private boolean animate; private View tint; private boolean isMic; private ImageView mic; private ImageView drawerLogo; private SearchListener listener; private MenuListener menuListener; private FrameLayout rootLayout; private String logoText; private ProgressBar pb; private ArrayList initialResults; private boolean searchWithoutSuggestions = true; private boolean isVoiceRecognitionIntentSupported; private VoiceRecognitionListener voiceRecognitionListener; private Activity mContainerActivity; private Fragment mContainerFragment; private android.support.v4.app.Fragment mContainerSupportFragment; /** * Create a new searchbox * @param context Context */ public SearchBox(Context context) { this(context, null); } /** * Create a searchbox with params * @param context Context * @param attrs Attributes */ public SearchBox(Context context, AttributeSet attrs) { this(context, attrs, 0); } /** * Create a searchbox with params and a style * @param context Context * @param attrs Attributes * @param defStyle Style */ public SearchBox(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); inflate(context, R.layout.searchbox, this); this.searchOpen = false; this.isMic = true; this.materialMenu = (MaterialMenuView) findViewById(R.id.material_menu_button); this.logo = (TextView) findViewById(R.id.logo); this.search = (EditText) findViewById(R.id.search); this.results = (ListView) findViewById(R.id.results); this.context = context; this.pb = (ProgressBar) findViewById(R.id.pb); this.mic = (ImageView) findViewById(R.id.mic); this.drawerLogo = (ImageView) findViewById(R.id.drawer_logo); materialMenu.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (searchOpen) { toggleSearch(); } else { if (menuListener != null) menuListener.onMenuClick(); } } }); resultList = new ArrayList(); results.setAdapter(new SearchAdapter(context, resultList)); animate = true; isVoiceRecognitionIntentSupported = isIntentAvailable(context, new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)); logo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { toggleSearch(); } }); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ RelativeLayout searchRoot = (RelativeLayout) findViewById(R.id.search_root); LayoutTransition lt = new LayoutTransition(); lt.setDuration(100); searchRoot.setLayoutTransition(lt); } searchables = new ArrayList(); search.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { search(getSearchText()); return true; } return false; } }); search.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { if (TextUtils.isEmpty(getSearchText())) { toggleSearch(); } else { search(getSearchText()); } return true; } return false; } }); logoText = "Logo"; micStateChanged(); mic.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (voiceRecognitionListener != null) { voiceRecognitionListener.onClick(); } else { micClick(); } } }); } public boolean isSearchOpened() { return searchOpen; } private static boolean isIntentAvailable(Context context, Intent intent) { PackageManager mgr = context.getPackageManager(); List list = mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } /*** * Reveal the searchbox from a menu item. Specify the menu item id and pass the activity so the item can be found * @param id View ID * @param activity Activity */ public void revealFromMenuItem(int id, Activity activity) { setVisibility(View.VISIBLE); View menuButton = activity.findViewById(id); if (menuButton != null) { FrameLayout layout = (FrameLayout) activity.getWindow().getDecorView() .findViewById(android.R.id.content); if (layout.findViewWithTag("searchBox") == null) { int[] location = new int[2]; menuButton.getLocationInWindow(location); revealFrom((float) location[0], (float) location[1], activity, this); } } } /*** * Hide the searchbox using the circle animation. Can be called regardless of result list length * @param activity Activity */ public void hideCircularly(Activity activity){ Display display = activity.getWindowManager().getDefaultDisplay(); Point size = new Point(); final FrameLayout layout = (FrameLayout) activity.getWindow().getDecorView() .findViewById(android.R.id.content); RelativeLayout root = (RelativeLayout) findViewById(R.id.search_root); display.getSize(size); Resources r = getResources(); float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 96, r.getDisplayMetrics()); int cx = layout.getLeft() + layout.getRight(); int cy = layout.getTop(); int finalRadius = (int) Math.max(layout.getWidth()*1.5, px); SupportAnimator animator = ViewAnimationUtils.createCircularReveal( root, cx, cy, 0, finalRadius); animator.setInterpolator(new ReverseInterpolator()); animator.setDuration(250); animator.start(); animator.addListener(new SupportAnimator.AnimatorListener(){ @Override public void onAnimationStart() { } @Override public void onAnimationEnd() { setVisibility(View.GONE); } @Override public void onAnimationCancel() { } @Override public void onAnimationRepeat() { } }); } /*** * Toggle the searchbox's open/closed state manually */ public void toggleSearch() { if (searchOpen) { if (TextUtils.isEmpty(getSearchText())) { setLogoTextInt(logoText); } closeSearch(); } else { openSearch(true); } searchOpen = !searchOpen; } /*** * Hide the search results manually */ public void hideResults(){ this.search.setVisibility(View.GONE); this.results.setVisibility(View.GONE); } /*** * Start the voice input activity manually */ public void startVoiceRecognition() { if (isMicEnabled()) { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, context.getString(R.string.speak_now)); if (mContainerActivity != null) { mContainerActivity.startActivityForResult(intent, VOICE_RECOGNITION_CODE); } else if (mContainerFragment != null) { mContainerFragment.startActivityForResult(intent, VOICE_RECOGNITION_CODE); } else if (mContainerSupportFragment != null) { mContainerSupportFragment.startActivityForResult(intent, VOICE_RECOGNITION_CODE); } } } /*** * Enable voice recognition for Activity * @param context Context */ public void enableVoiceRecognition(Activity context) { mContainerActivity = context; micStateChanged(); } /*** * Enable voice recognition for Fragment * @param context Fragment */ public void enableVoiceRecognition(Fragment context) { mContainerFragment = context; micStateChanged(); } /*** * Enable voice recognition for Support Fragment * @param context Fragment */ public void enableVoiceRecognition(android.support.v4.app.Fragment context) { mContainerSupportFragment = context; micStateChanged(); } private boolean isMicEnabled() { return isVoiceRecognitionIntentSupported && (mContainerActivity != null || mContainerSupportFragment != null || mContainerFragment != null); } private void micStateChanged() { mic.setVisibility((!isMic || isMicEnabled()) ? VISIBLE : INVISIBLE); } private void micStateChanged(boolean isMic) { this.isMic = isMic; micStateChanged(); } /*** * Set whether to show the progress bar spinner * @param show Whether to show */ public void showLoading(boolean show){ if(show){ pb.setVisibility(View.VISIBLE); mic.setVisibility(View.INVISIBLE); }else{ pb.setVisibility(View.INVISIBLE); mic.setVisibility(View.VISIBLE); } } /*** * Mandatory method for the onClick event */ public void micClick() { if (!isMic) { setSearchString(""); } else { startVoiceRecognition(); } } /*** * Populate the searchbox with words, in an arraylist. Used by the voice input * @param matches Matches */ public void populateEditText(ArrayList matches) { toggleSearch(); String text = ""; for (int x = 0; x < matches.size(); x++) { text = text + matches.get(x) + " "; } text = text.trim(); setSearchString(text); search(text); } /*** * Force an update of the results */ public void updateResults() { resultList.clear(); int count = 0; for (int x = 0; x < searchables.size(); x++) { if (searchables.get(x).title.toLowerCase().startsWith( getSearchText().toLowerCase()) && count < 5) { addResult(searchables.get(x)); count++; } } if (resultList.size() == 0) { results.setVisibility(View.GONE); } else { results.setVisibility(View.VISIBLE); } } /*** * * Set the results that are shown (up to 5) when the searchbox is opened with no text * @param results Results */ public void setInitialResults(ArrayList results){ this.initialResults = results; } /*** * Set whether the menu button should be shown. Particularly useful for apps that adapt to screen sizes * @param visibility Whether to show */ public void setMenuVisibility(int visibility){ materialMenu.setVisibility(visibility); } /*** * Set the menu listener * @param menuListener MenuListener */ public void setMenuListener(MenuListener menuListener) { this.menuListener = menuListener; } /*** * Set the search listener * @param listener SearchListener */ public void setSearchListener(SearchListener listener) { this.listener = listener; } /*** * Set whether to search without suggestions being available (default is true). Disable if your app only works with provided options * @param state Whether to show */ public void setSearchWithoutSuggestions(boolean state){ this.searchWithoutSuggestions = state; } /*** * Set the maximum length of the searchbox's edittext * @param length Length */ public void setMaxLength(int length) { search.setFilters(new InputFilter[] { new InputFilter.LengthFilter( length) }); } /*** * Set the text of the logo (default text when closed) * @param text Text */ public void setLogoText(String text) { this.logoText = text; setLogoTextInt(text); } /*** * Set the image drawable of the drawer icon logo (do not set if you have not hidden the menu icon) * @param icon Icon */ public void setDrawerLogo(Drawable icon) { drawerLogo.setImageDrawable(icon); } /*** * Get the searchbox's current text * @return Text */ public String getSearchText() { return search.getText().toString(); } /*** * Set the searchbox's current text manually * @param text Text */ public void setSearchString(String text) { search.setText(text); } /*** * Add a result * @param result SearchResult */ private void addResult(SearchResult result) { if (resultList != null && resultList.size() < 6) { resultList.add(result); ((SearchAdapter) results.getAdapter()).notifyDataSetChanged(); } } /*** * Clear all the results */ public void clearResults() { if (resultList != null) { resultList.clear(); ((SearchAdapter) results.getAdapter()).notifyDataSetChanged(); } listener.onSearchCleared(); } /*** * Return the number of results that are currently shown * @return Number of Results */ public int getNumberOfResults() { if (resultList != null)return resultList.size(); return 0; } /*** * Set the searchable items from a list (replaces any current items) */ public void setSearchables(ArrayList searchables){ this.searchables = searchables; } /*** * Add a searchable item * @param searchable SearchResult */ public void addSearchable(SearchResult searchable) { if (!searchables.contains(searchable)) searchables.add(searchable); } /*** * Remove a searchable item * @param searchable SearchResult */ public void removeSearchable(SearchResult searchable) { if (searchables.contains(searchable)) searchables.remove(search); } /*** * Clear all searchable items */ public void clearSearchable() { searchables.clear(); } /*** * Get all searchable items * @return ArrayList of SearchResults */ public ArrayList getSearchables() { return searchables; } private void revealFrom(float x, float y, Activity a, SearchBox s) { FrameLayout layout = (FrameLayout) a.getWindow().getDecorView() .findViewById(android.R.id.content); RelativeLayout root = (RelativeLayout) s.findViewById(R.id.search_root); Resources r = getResources(); float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 96, r.getDisplayMetrics()); int cx = layout.getLeft() + layout.getRight(); int cy = layout.getTop(); int finalRadius = (int) Math.max(layout.getWidth(), px); SupportAnimator animator = ViewAnimationUtils.createCircularReveal( root, cx, cy, 0, finalRadius); animator.setInterpolator(new AccelerateDecelerateInterpolator()); animator.setDuration(500); animator.addListener(new SupportAnimator.AnimatorListener(){ @Override public void onAnimationCancel() { } @Override public void onAnimationEnd() { toggleSearch(); } @Override public void onAnimationRepeat() { } @Override public void onAnimationStart() { } }); animator.start(); } private void search(SearchResult result) { if(!searchWithoutSuggestions && getNumberOfResults() == 0)return; setSearchString(result.title); if (!TextUtils.isEmpty(getSearchText())) { setLogoTextInt(result.title); if (listener != null) listener.onSearch(result.title); } else { setLogoTextInt(logoText); } toggleSearch(); } private void openSearch(Boolean openKeyboard) { this.materialMenu.animateState(IconState.ARROW); this.logo.setVisibility(View.GONE); this.drawerLogo.setVisibility(View.GONE); this.search.setVisibility(View.VISIBLE); search.requestFocus(); this.results.setVisibility(View.VISIBLE); animate = true; results.setAdapter(new SearchAdapter(context, resultList)); search.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { if (s.length() > 0) { micStateChanged(false); mic.setImageDrawable(context.getResources().getDrawable( R.drawable.ic_clear)); updateResults(); } else { micStateChanged(true); mic.setImageDrawable(context.getResources().getDrawable( R.drawable.ic_action_mic)); if(initialResults != null){ setInitialResults(); }else{ updateResults(); } } if (listener != null) listener.onSearchTermChanged(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); results.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { SearchResult result = resultList.get(arg2); search(result); } }); if(initialResults != null){ setInitialResults(); }else{ updateResults(); } if (listener != null) listener.onSearchOpened(); if (getSearchText().length() > 0) { micStateChanged(false); mic.setImageDrawable(context.getResources().getDrawable( R.drawable.ic_clear)); } if (openKeyboard) { InputMethodManager inputMethodManager = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.toggleSoftInputFromWindow( getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0); } } private void setInitialResults(){ resultList.clear(); int count = 0; for (int x = 0; x < initialResults.size(); x++) { if (count < 5) { addResult(initialResults.get(x)); count++; } } if (resultList.size() == 0) { results.setVisibility(View.GONE); } else { results.setVisibility(View.VISIBLE); } } private void closeSearch() { this.materialMenu.animateState(IconState.BURGER); this.logo.setVisibility(View.VISIBLE); this.drawerLogo.setVisibility(View.VISIBLE); this.search.setVisibility(View.GONE); this.results.setVisibility(View.GONE); if (tint != null && rootLayout != null) { rootLayout.removeView(tint); } if (listener != null) listener.onSearchClosed(); micStateChanged(true); mic.setImageDrawable(context.getResources().getDrawable( R.drawable.ic_action_mic)); InputMethodManager inputMethodManager = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(getApplicationWindowToken(), 0); } private void setLogoTextInt(String text) { logo.setText(text); } private void search(String text) { SearchResult option = new SearchResult(text, null); search(option); } class SearchAdapter extends ArrayAdapter { public SearchAdapter(Context context, ArrayList options) { super(context, 0, options); } int count = 0; @Override public View getView(int position, View convertView, ViewGroup parent) { SearchResult option = getItem(position); if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate( R.layout.search_option, parent, false); if (animate) { Animation anim = AnimationUtils.loadAnimation(context, R.anim.anim_down); anim.setDuration(400); convertView.startAnimation(anim); if (count == this.getCount()) { animate = false; } count++; } } View border = convertView.findViewById(R.id.border); if (position == 0) { border.setVisibility(View.VISIBLE); } else { border.setVisibility(View.GONE); } final TextView title = (TextView) convertView .findViewById(R.id.title); title.setText(option.title); ImageView icon = (ImageView) convertView.findViewById(R.id.icon); if (option.icon != null) { icon.setImageDrawable(option.icon); } else { icon.setImageResource(option.drawableResId); } ImageView up = (ImageView) convertView.findViewById(R.id.up); up.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setSearchString(title.getText().toString()); search.setSelection(search.getText().length()); } }); return convertView; } } public interface SearchListener { /** * Called when the searchbox is opened */ public void onSearchOpened(); /** * Called when the clear button is pressed */ public void onSearchCleared(); /** * Called when the searchbox is closed */ public void onSearchClosed(); /** * Called when the searchbox's edittext changes */ public void onSearchTermChanged(); /** * Called when a search happens, with a result * @param result */ public void onSearch(String result); } public interface MenuListener { /** * Called when the menu button is pressed */ public void onMenuClick(); } public interface VoiceRecognitionListener { /** * Called when the menu button is pressed */ public void onClick(); } } ================================================ FILE: libraries/PersistentSearch/src/main/java/com/quinny898/library/persistentsearch/SearchResult.java ================================================ package com.quinny898.library.persistentsearch; import android.graphics.drawable.Drawable; import android.support.annotation.DrawableRes; public class SearchResult { public String title; public Drawable icon; public int drawableResId; /** * Create a search result with text and an icon * @param title * @param icon */ public SearchResult(String title, Drawable icon) { this.title = title; this.icon = icon; } public SearchResult(String title, @DrawableRes int drawableResId) { this.title = title; this.drawableResId = drawableResId; } /** * Return the title of the result */ @Override public String toString() { return title; } } ================================================ FILE: libraries/PersistentSearch/src/main/java/io/codetail/animation/RevealAnimator.java ================================================ package io.codetail.animation; import android.annotation.TargetApi; import android.graphics.Rect; import android.os.Build; import android.view.View; import com.nineoldandroids.animation.Animator; import java.lang.ref.WeakReference; import static io.codetail.animation.ViewAnimationUtils.SimpleAnimationListener; /** * @hide */ public interface RevealAnimator{ public void setClipOutlines(boolean clip); public void setCenter(float cx, float cy); public void setTarget(View target); public void setRevealRadius(float value); public float getRevealRadius(); public void invalidate(Rect bounds); static class RevealFinishedGingerbread extends SimpleAnimationListener { WeakReference mReference; volatile Rect mInvalidateBounds; RevealFinishedGingerbread(RevealAnimator target, Rect bounds) { mReference = new WeakReference<>(target); mInvalidateBounds = bounds; } @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); RevealAnimator target = mReference.get(); if(target == null){ return; } target.setClipOutlines(false); target.setCenter(0, 0); target.setTarget(null); target.invalidate(mInvalidateBounds); } } static class RevealFinishedIceCreamSandwich extends SimpleAnimationListener { WeakReference mReference; volatile Rect mInvalidateBounds; int mLayerType; @TargetApi(Build.VERSION_CODES.HONEYCOMB) RevealFinishedIceCreamSandwich(RevealAnimator target, Rect bounds) { mReference = new WeakReference<>(target); mInvalidateBounds = bounds; mLayerType = ((View) target).getLayerType(); } @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void onAnimationStart(Animator animation) { super.onAnimationStart(animation); ((View) mReference.get()).setLayerType(View.LAYER_TYPE_SOFTWARE, null); } @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); ((View) mReference.get()).setLayerType(mLayerType, null); RevealAnimator target = mReference.get(); if(target == null){ return; } target.setClipOutlines(false); target.setCenter(0, 0); target.setTarget(null); target.invalidate(mInvalidateBounds); } } static class RevealFinishedJellyBeanMr1 extends SimpleAnimationListener { WeakReference mReference; volatile Rect mInvalidateBounds; int mLayerType; @TargetApi(Build.VERSION_CODES.HONEYCOMB) RevealFinishedJellyBeanMr1(RevealAnimator target, Rect bounds) { mReference = new WeakReference<>(target); mInvalidateBounds = bounds; mLayerType = ((View) target).getLayerType(); } @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void onAnimationStart(Animator animation) { super.onAnimationStart(animation); ((View) mReference.get()).setLayerType(View.LAYER_TYPE_HARDWARE, null); } @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); ((View) mReference.get()).setLayerType(mLayerType, null); RevealAnimator target = mReference.get(); if(target == null){ return; } target.setClipOutlines(false); target.setCenter(0, 0); target.setTarget(null); target.invalidate(mInvalidateBounds); } } } ================================================ FILE: libraries/PersistentSearch/src/main/java/io/codetail/animation/ReverseInterpolator.java ================================================ package io.codetail.animation; import android.view.animation.Interpolator; public class ReverseInterpolator implements Interpolator { public float getInterpolation(float t) { t = Math.abs(t -1f); float x = t*2.0f; if (t<0.5f) return 0.5f*x*x*x*x*x; x = (t-0.5f)*2-1; return 0.5f*x*x*x*x*x+1; } } ================================================ FILE: libraries/PersistentSearch/src/main/java/io/codetail/animation/SupportAnimator.java ================================================ package io.codetail.animation; import android.view.animation.Interpolator; public abstract class SupportAnimator { /** * @return true if using native android animation framework, otherwise is * nineoldandroids */ public abstract boolean isNativeAnimator(); /** * @return depends from {@link android.os.Build.VERSION} if sdk version * {@link android.os.Build.VERSION_CODES#LOLLIPOP} and greater will return * {@link android.animation.Animator} otherwise {@link com.nineoldandroids.animation.Animator} */ public abstract Object get(); /** * Starts this animation. If the animation has a nonzero startDelay, the animation will start * running after that delay elapses. A non-delayed animation will have its initial * value(s) set immediately, followed by calls to * {@link android.animation.Animator.AnimatorListener#onAnimationStart(android.animation.Animator)} * for any listeners of this animator. * *

The animation started by calling this method will be run on the thread that called * this method. This thread should have a Looper on it (a runtime exception will be thrown if * this is not the case). Also, if the animation will animate * properties of objects in the view hierarchy, then the calling thread should be the UI * thread for that view hierarchy.

* */ public abstract void start(); /** * Sets the duration of the animation. * * @param duration The length of the animation, in milliseconds. */ public abstract void setDuration(int duration); /** * The time interpolator used in calculating the elapsed fraction of the * animation. The interpolator determines whether the animation runs with * linear or non-linear motion, such as acceleration and deceleration. The * default value is {@link android.view.animation.AccelerateDecelerateInterpolator}. * * @param value the interpolator to be used by this animation */ public abstract void setInterpolator(Interpolator value); /** * Adds a listener to the set of listeners that are sent events through the life of an * animation, such as start, repeat, and end. * * @param listener the listener to be added to the current set of listeners for this animation. */ public abstract void addListener(AnimatorListener listener); /** * Returns whether this Animator is currently running (having been started and gone past any * initial startDelay period and not yet ended). * * @return Whether the Animator is running. */ public abstract boolean isRunning(); /** *

An animation listener receives notifications from an animation. * Notifications indicate animation related events, such as the end or the * repetition of the animation.

*/ public static interface AnimatorListener { /** *

Notifies the start of the animation.

*/ void onAnimationStart(); /** *

Notifies the end of the animation. This callback is not invoked * for animations with repeat count set to INFINITE.

*/ void onAnimationEnd(); /** *

Notifies the cancellation of the animation. This callback is not invoked * for animations with repeat count set to INFINITE.

*/ void onAnimationCancel(); /** *

Notifies the repetition of the animation.

*/ void onAnimationRepeat(); } } ================================================ FILE: libraries/PersistentSearch/src/main/java/io/codetail/animation/SupportAnimatorLollipop.java ================================================ package io.codetail.animation; import android.animation.Animator; import android.annotation.TargetApi; import android.os.Build; import android.view.animation.Interpolator; import java.lang.ref.WeakReference; @TargetApi(Build.VERSION_CODES.HONEYCOMB) final class SupportAnimatorLollipop extends SupportAnimator{ WeakReference mNativeAnimator; SupportAnimatorLollipop(Animator animator) { mNativeAnimator = new WeakReference(animator); } @Override public boolean isNativeAnimator() { return true; } @Override public Object get() { return mNativeAnimator; } @Override public void start() { Animator a = mNativeAnimator.get(); if(a != null) { a.start(); } } @Override public void setDuration(int duration) { Animator a = mNativeAnimator.get(); if(a != null) { a.setDuration(duration); } } @Override public void setInterpolator(Interpolator value) { Animator a = mNativeAnimator.get(); if(a != null) { a.setInterpolator(value); } } @Override public void addListener(final AnimatorListener listener) { Animator a = mNativeAnimator.get(); if(a == null) { return; } if(listener == null){ a.addListener(null); return; } a.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { listener.onAnimationStart(); } @Override public void onAnimationEnd(Animator animation) { listener.onAnimationEnd(); } @Override public void onAnimationCancel(Animator animation) { listener.onAnimationCancel(); } @Override public void onAnimationRepeat(Animator animation) { listener.onAnimationRepeat(); } }); } @Override public boolean isRunning() { Animator a = mNativeAnimator.get(); return a != null && a.isRunning(); } } ================================================ FILE: libraries/PersistentSearch/src/main/java/io/codetail/animation/SupportAnimatorPreL.java ================================================ package io.codetail.animation; import android.view.animation.Interpolator; import com.nineoldandroids.animation.Animator; import java.lang.ref.WeakReference; final class SupportAnimatorPreL extends SupportAnimator { WeakReference mSupportFramework; SupportAnimatorPreL(Animator animator) { mSupportFramework = new WeakReference(animator); } @Override public boolean isNativeAnimator() { return false; } @Override public Object get() { return mSupportFramework.get(); } @Override public void start() { Animator a = mSupportFramework.get(); if(a != null) { a.start(); } } @Override public void setDuration(int duration) { Animator a = mSupportFramework.get(); if(a != null) { a.setDuration(duration); } } @Override public void setInterpolator(Interpolator value) { Animator a = mSupportFramework.get(); if(a != null) { a.setInterpolator(value); } } @Override public void addListener(final AnimatorListener listener) { Animator a = mSupportFramework.get(); if(a == null) { return; } if(listener == null){ a.addListener(null); return; } a.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { listener.onAnimationStart(); } @Override public void onAnimationEnd(Animator animation) { listener.onAnimationEnd(); } @Override public void onAnimationCancel(Animator animation) { listener.onAnimationCancel(); } @Override public void onAnimationRepeat(Animator animation) { listener.onAnimationRepeat(); } }); } @Override public boolean isRunning() { Animator a = mSupportFramework.get(); return a != null && a.isRunning(); } } ================================================ FILE: libraries/PersistentSearch/src/main/java/io/codetail/animation/ViewAnimationUtils.java ================================================ package io.codetail.animation; import android.annotation.TargetApi; import android.graphics.Rect; import android.os.Build; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.ObjectAnimator; import com.nineoldandroids.view.ViewHelper; import com.nineoldandroids.view.ViewPropertyAnimator; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.LOLLIPOP; public class ViewAnimationUtils { private final static boolean LOLLIPOP_PLUS = SDK_INT >= LOLLIPOP; public static final int SCALE_UP_DURATION = 500; /** * Returns an Animator which can animate a clipping circle. *

* Any shadow cast by the View will respect the circular clip from this animator. *

* Only a single non-rectangular clip can be applied on a View at any time. * Views clipped by a circular reveal animation take priority over * {@link android.view.View#setClipToOutline(boolean) View Outline clipping}. *

* Note that the animation returned here is a one-shot animation. It cannot * be re-used, and once started it cannot be paused or resumed. * * @param view The View will be clipped to the animating circle. * @param centerX The x coordinate of the center of the animating circle. * @param centerY The y coordinate of the center of the animating circle. * @param startRadius The starting radius of the animating circle. * @param endRadius The ending radius of the animating circle. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public static SupportAnimator createCircularReveal(View view, int centerX, int centerY, float startRadius, float endRadius) { if(LOLLIPOP_PLUS){ return new SupportAnimatorLollipop(android.view.ViewAnimationUtils .createCircularReveal(view, centerX, centerY, startRadius, endRadius)); } if(!(view.getParent() instanceof RevealAnimator)){ throw new IllegalArgumentException("View must be inside RevealFrameLayout or RevealLinearLayout."); } RevealAnimator revealLayout = (RevealAnimator) view.getParent(); revealLayout.setTarget(view); revealLayout.setCenter(centerX, centerY); Rect bounds = new Rect(); view.getHitRect(bounds); ObjectAnimator reveal = ObjectAnimator.ofFloat(revealLayout, "revealRadius", startRadius, endRadius); reveal.addListener(getRevealFinishListener(revealLayout, bounds)); return new SupportAnimatorPreL(reveal); } static Animator.AnimatorListener getRevealFinishListener(RevealAnimator target, Rect bounds){ if(SDK_INT >= 17){ return new RevealAnimator.RevealFinishedJellyBeanMr1(target, bounds); }else if(SDK_INT >= 14){ return new RevealAnimator.RevealFinishedIceCreamSandwich(target, bounds); }else { return new RevealAnimator.RevealFinishedGingerbread(target, bounds); } } /** * Lifting view * * @param view The animation target * @param baseRotation initial Rotation X in 3D space * @param fromY initial Y position of view * @param duration aniamtion duration * @param startDelay start delay before animation begin */ public static void liftingFromBottom(View view, float baseRotation, float fromY, int duration, int startDelay){ ViewHelper.setRotationX(view, baseRotation); ViewHelper.setTranslationY(view, fromY); ViewPropertyAnimator .animate(view) .setInterpolator(new AccelerateDecelerateInterpolator()) .setDuration(duration) .setStartDelay(startDelay) .rotationX(0) .translationY(0) .start(); } /** * Lifting view * * @param view The animation target * @param baseRotation initial Rotation X in 3D space * @param duration aniamtion duration * @param startDelay start delay before animation begin */ public static void liftingFromBottom(View view, float baseRotation, int duration, int startDelay){ ViewHelper.setRotationX(view, baseRotation); ViewHelper.setTranslationY(view, view.getHeight() / 3); ViewPropertyAnimator .animate(view) .setInterpolator(new AccelerateDecelerateInterpolator()) .setDuration(duration) .setStartDelay(startDelay) .rotationX(0) .translationY(0) .start(); } /** * Lifting view * * @param view The animation target * @param baseRotation initial Rotation X in 3D space * @param duration aniamtion duration */ public static void liftingFromBottom(View view, float baseRotation, int duration){ ViewHelper.setRotationX(view, baseRotation); ViewHelper.setTranslationY(view, view.getHeight() / 3); ViewPropertyAnimator .animate(view) .setInterpolator(new AccelerateDecelerateInterpolator()) .setDuration(duration) .rotationX(0) .translationY(0) .start(); } public static class SimpleAnimationListener implements Animator.AnimatorListener{ @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } } } ================================================ FILE: libraries/PersistentSearch/src/main/java/io/codetail/widget/RevealFrameLayout.java ================================================ package io.codetail.widget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Path; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; import io.codetail.animation.RevealAnimator; public class RevealFrameLayout extends FrameLayout implements RevealAnimator{ Path mRevealPath; boolean mClipOutlines; float mCenterX; float mCenterY; float mRadius; View mTarget; public RevealFrameLayout(Context context) { this(context, null); } public RevealFrameLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RevealFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mRevealPath = new Path(); } /** * Animation target * * @hide */ @Override public void setTarget(View view){ mTarget = view; } /** * Epicenter of animation circle reveal * * @hide */ @Override public void setCenter(float centerX, float centerY){ mCenterX = centerX; mCenterY = centerY; } /** * Flag that animation is enabled * * @hide */ @Override public void setClipOutlines(boolean clip){ mClipOutlines = clip; } /** * Circle radius size * * @hide */ @Override public void setRevealRadius(float radius){ mRadius = radius; invalidate(); } /** * Circle radius size * * @hide */ @Override public float getRevealRadius(){ return mRadius; } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { if(!mClipOutlines && child != mTarget) return super.drawChild(canvas, child, drawingTime); final int state = canvas.save(); mRevealPath.reset(); mRevealPath.addCircle(mCenterX, mCenterY, mRadius, Path.Direction.CW); canvas.clipPath(mRevealPath); boolean isInvalided = super.drawChild(canvas, child, drawingTime); canvas.restoreToCount(state); return isInvalided; } } ================================================ FILE: libraries/PersistentSearch/src/main/java/io/codetail/widget/RevealLinearLayout.java ================================================ package io.codetail.widget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Path; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import io.codetail.animation.RevealAnimator; public class RevealLinearLayout extends LinearLayout implements RevealAnimator{ Path mRevealPath; boolean mClipOutlines; float mCenterX; float mCenterY; float mRadius; View mTarget; public RevealLinearLayout(Context context) { this(context, null); } public RevealLinearLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RevealLinearLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs); mRevealPath = new Path(); } /** * @hide */ @Override public void setTarget(View view){ mTarget = view; } /** * @hide */ @Override public void setCenter(float centerX, float centerY){ mCenterX = centerX; mCenterY = centerY; } /** * @hide */ @Override public void setClipOutlines(boolean clip){ mClipOutlines = clip; } /** * @hide */ @Override public void setRevealRadius(float radius){ mRadius = radius; invalidate(); } /** * @hide */ @Override public float getRevealRadius(){ return mRadius; } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { if (!mClipOutlines && child != mTarget) return super.drawChild(canvas, child, drawingTime); final int state = canvas.save(); mRevealPath.reset(); mRevealPath.addCircle(mCenterX, mCenterY, mRadius, Path.Direction.CW); canvas.clipPath(mRevealPath); boolean isInvalided = super.drawChild(canvas, child, drawingTime); canvas.restoreToCount(state); return isInvalided; } } ================================================ FILE: libraries/PersistentSearch/src/main/res/anim/anim_down.xml ================================================ ================================================ FILE: libraries/PersistentSearch/src/main/res/layout/search_option.xml ================================================ ================================================ FILE: libraries/PersistentSearch/src/main/res/layout/searchbox.xml ================================================ ================================================ FILE: libraries/PersistentSearch/src/main/res/values/strings.xml ================================================ Speak now ================================================ FILE: libraries/PersistentSearch/src/main/res/values/styles.xml ================================================ ================================================ FILE: settings.gradle ================================================ include ':app', ':libraries:PersistentSearch'