Repository: billthefarmer/editor Branch: master Commit: 74d00f15570a Files: 168 Total size: 617.7 KB Directory structure: gitextract_btz8p0l7/ ├── .github/ │ └── workflows/ │ ├── build.yml │ └── release.yml ├── .gitignore ├── Charset.md ├── Chooser.md ├── LICENSE ├── Mode.md ├── README.md ├── Syntax.md ├── build.gradle ├── docs/ │ ├── 404.html │ ├── categories/ │ │ └── index.xml │ ├── css/ │ │ ├── custom.css │ │ └── styles.css │ ├── index.html │ ├── index.xml │ ├── introduction/ │ │ └── index.xml │ ├── sitemap.xml │ ├── tags/ │ │ └── index.xml │ └── using/ │ └── index.xml ├── fastlane/ │ └── metadata/ │ └── android/ │ ├── en/ │ │ ├── changelogs/ │ │ │ ├── 1193.txt │ │ │ ├── 162.txt │ │ │ ├── 163.txt │ │ │ ├── 164.txt │ │ │ ├── 165.txt │ │ │ ├── 166.txt │ │ │ ├── 167.txt │ │ │ ├── 168.txt │ │ │ ├── 169.txt │ │ │ ├── 170.txt │ │ │ ├── 171.txt │ │ │ ├── 172.txt │ │ │ ├── 173.txt │ │ │ ├── 174.txt │ │ │ ├── 175.txt │ │ │ ├── 176.txt │ │ │ ├── 177.txt │ │ │ ├── 178.txt │ │ │ ├── 179.txt │ │ │ ├── 180.txt │ │ │ ├── 181.txt │ │ │ ├── 182.txt │ │ │ ├── 183.txt │ │ │ ├── 184.txt │ │ │ ├── 185.txt │ │ │ ├── 186.txt │ │ │ ├── 187.txt │ │ │ ├── 188.txt │ │ │ ├── 189.txt │ │ │ ├── 190.txt │ │ │ ├── 191.txt │ │ │ ├── 192.txt │ │ │ ├── 194.txt │ │ │ ├── 195.txt │ │ │ ├── 196.txt │ │ │ └── 197.txt │ │ ├── full_description.txt │ │ ├── short_description.txt │ │ └── title.txt │ ├── hu/ │ │ ├── changelogs/ │ │ │ ├── 162.txt │ │ │ ├── 163.txt │ │ │ ├── 164.txt │ │ │ ├── 165.txt │ │ │ ├── 166.txt │ │ │ ├── 167.txt │ │ │ ├── 168.txt │ │ │ ├── 169.txt │ │ │ ├── 170.txt │ │ │ └── 171.txt │ │ ├── full_description.txt │ │ ├── short_description.txt │ │ └── title.txt │ └── ja/ │ ├── changelogs/ │ │ ├── 162.txt │ │ ├── 163.txt │ │ ├── 164.txt │ │ ├── 165.txt │ │ ├── 166.txt │ │ ├── 167.txt │ │ ├── 168.txt │ │ ├── 169.txt │ │ ├── 170.txt │ │ ├── 171.txt │ │ ├── 172.txt │ │ └── 173.txt │ ├── full_description.txt │ ├── short_description.txt │ └── title.txt ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat └── src/ └── main/ ├── AndroidManifest.xml ├── java/ │ ├── android/ │ │ └── support/ │ │ └── v4/ │ │ └── content/ │ │ └── FileProvider.java │ ├── com/ │ │ └── ibm/ │ │ └── icu/ │ │ └── text/ │ │ ├── CharsetDetector.java │ │ ├── CharsetMatch.java │ │ ├── CharsetRecog_2022.java │ │ ├── CharsetRecog_UTF8.java │ │ ├── CharsetRecog_Unicode.java │ │ ├── CharsetRecog_mbcs.java │ │ ├── CharsetRecog_sbcs.java │ │ └── CharsetRecognizer.java │ └── org/ │ └── billthefarmer/ │ └── editor/ │ ├── Editor.java │ ├── FileAdapter.java │ ├── FileUtils.java │ ├── NewFile.java │ └── OpenFile.java └── res/ ├── color/ │ └── text_color_retro.xml ├── drawable/ │ ├── ic_add_black_24dp.xml │ ├── ic_add_white_24dp.xml │ ├── ic_edit_black_24dp.xml │ ├── ic_edit_white_24dp.xml │ ├── ic_folder_open_black_24dp.xml │ ├── ic_folder_open_white_24dp.xml │ ├── ic_image_black_24dp.xml │ ├── ic_image_white_24dp.xml │ ├── ic_list_black_24dp.xml │ ├── ic_list_white_24dp.xml │ ├── ic_reply_black_24dp.xml │ ├── ic_reply_white_24dp.xml │ ├── ic_save_black_24dp.xml │ ├── ic_save_white_24dp.xml │ ├── ic_sd_storage_black_24dp.xml │ ├── ic_sd_storage_white_24dp.xml │ ├── ic_stop_black_24dp.xml │ ├── ic_stop_white_24dp.xml │ ├── ic_videocam_black_24dp.xml │ ├── ic_videocam_white_24dp.xml │ ├── ic_volume_up_black_24dp.xml │ └── ic_volume_up_white_24dp.xml ├── layout/ │ ├── custom.xml │ ├── edit.xml │ ├── file.xml │ ├── open_file.xml │ ├── save_path.xml │ ├── seek_bar.xml │ └── wrap.xml ├── menu/ │ └── main.xml ├── values/ │ ├── arrays.xml │ ├── attrs.xml │ ├── colours.xml │ ├── strings.xml │ └── styles.xml ├── values-ar/ │ └── strings.xml ├── values-be/ │ └── strings.xml ├── values-de/ │ └── strings.xml ├── values-el/ │ └── strings.xml ├── values-es/ │ └── strings.xml ├── values-eu/ │ └── strings.xml ├── values-fa/ │ └── strings.xml ├── values-fr/ │ └── strings.xml ├── values-hu/ │ └── strings.xml ├── values-is/ │ └── strings.xml ├── values-it/ │ └── strings.xml ├── values-ja/ │ └── strings.xml ├── values-ku-rIQ/ │ └── strings.xml ├── values-lv/ │ └── strings.xml ├── values-nl/ │ └── strings.xml ├── values-pl/ │ └── strings.xml ├── values-pt/ │ └── strings.xml ├── values-pt-rBR/ │ └── strings.xml ├── values-ru/ │ └── strings.xml ├── values-tr/ │ └── strings.xml ├── values-uk/ │ └── strings.xml ├── values-zh-rCN/ │ └── strings.xml ├── values-zh-rTW/ │ └── strings.xml └── xml/ ├── filepaths.xml └── shortcuts.xml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/build.yml ================================================ # Build on push and PR events on: push: branches: - master tags-ignore: - '*' pull_request: jobs: build: runs-on: ubuntu-latest steps: - name: Checkout uses: "actions/checkout@v3" - name: Build with Gradle run: ./gradlew build ================================================ FILE: .github/workflows/release.yml ================================================ # Release on new tags on: push: tags: - 'v*' jobs: release: runs-on: ubuntu-latest steps: - uses: "actions/checkout@v3" - name: Get the tag version id: version run: echo ::set-output name=VERSION::${GITHUB_REF#refs/tags/v} - name: Create release id: create_release uses: actions/create-release@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: ${{ github.ref }} release_name: "Version ${{ steps.version.outputs.VERSION }}" body: "![Icon](src/main/res/drawable-xhdpi/ic_launcher.png)" ================================================ FILE: .gitignore ================================================ .gradle/ build/ local.properties *.iml .idea/ data/ *.orig *~ *.apk ================================================ FILE: Charset.md ================================================ # Character set ![Editor](https://github.com/billthefarmer/billthefarmer.github.io/raw/master/images/Editor-charset.png) ## Default The default character set is set to `UTF-8` on selecting **New** from the toolbar. It may be changed in the menu. Android defaults to `UTF-8`, don't use anything else unless you are sure what you are doing. ## Detection The current character set is optionally detected on reading a file by the detection code from [International Components for Unicode](https://unicode-org.github.io/icu/userguide/icu4j). If there are no accented characters or symbols in the text to give the detection algorithm something to work on it may not get it right. ## Saving Files will be saved using the current character set. To change it, use the **Charset** item in the menu, which shows the current set. **Caution** – If you add accented characters or symbols to the text, make sure to check the current character set before you save it. ## Mode line The character set may be set to `UTF-8` by using a mode line in the text. ``` # ed: cs:u ``` See [Mode line](Mode.md) for details. ================================================ FILE: Chooser.md ================================================ # File Chooser ![Editor](https://github.com/billthefarmer/billthefarmer.github.io/raw/master/images/Editor-chooser.png) The chooser shows a scrollable row of folder buttons and a list of files with icons. Files which appear to be media files, or are too large will be disabled and not selectable. Touch a folder button or folder to change folder, or a file to open a file. Hidden files beginning with a '.' will not appear. The parent folder, if it exists, will appear first in the list. Touch that folder to move up the directory tree. If a folder is not accessible, the chooser will show the parent folder, if it exists, and the external storage folder (`/storage/emulated/0`). Use the **Storage** button to open files using the android file manager. This should ensure that files on removeable SD cards can be saved using the **Save** button. The file manager may refuse to open some types of text files not recognised by android. ================================================ 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. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} 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: {project} Copyright (C) {year} {fullname} 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: Mode.md ================================================ # Mode line If a line of text is found within the first or last two or three lines of the file which matches the mode line pattern, the mode of the editor will be changed after the file is loaded. The pattern is one or more text or punctuation characters, white space, the text `ed:` followed by one or more option patterns separated by white space. ``` # ed: [[no]vw] [[no]ww] [[no]sg] [[no]hs] [cs:u] [th:l|d|s|w|b|r] [ts:l|m|s] [tf:m|p|s] ``` The initial text or punctuation characters are intended to be used to hide the mode line from compilers and interpreters by commenting it out. The option patterns are: * **[no]vw** – View files read only * **[no]ww** – Word wrap * **[no]sg** – Suggestions * **[no]hs** – Syntax highlighting * **cs:u** – Character set – UTF-8 * **th:l|d|s|w|b|r** – Theme – light, dark, system, white, black or retro * **ts:l|m|s** – Text size – large, medium or small * **tf:m|p|s** – Typeface – monospace, proportional (sans) or serif The mode line is read after the file is loaded and will change immediately, except in Android 6, Marshmallow due to an obscure bug. Rotate the device to change mode. ================================================ FILE: README.md ================================================ # ![Logo](src/main/res/drawable-hdpi/ic_launcher.png) Editor ![.github/workflows/build.yml](https://github.com/billthefarmer/editor/workflows/.github/workflows/build.yml/badge.svg) [![Release](https://img.shields.io/github/release/billthefarmer/editor.svg?logo=github)](https://github.com/billthefarmer/editor/releases) [Get it on F-Droid](https://f-droid.org/packages/org.billthefarmer.editor) Android simple generic text editor. The app is available from [F-Droid](https://f-droid.org/packages/org.billthefarmer.editor) and [here](https://github.com/billthefarmer/editor/releases) ### Issues There have been a number of issues raised on this app where users have obviously not read this README, looked at the [documentation](https://billthefarmer.github.io/editor/), or looked at old closed issues. Please read the README, read the [docs](https://billthefarmer.github.io/editor/), and look at the old issues before raising another one, you can search the issues from the box at the top. ### Large files Editor loads the whole of file to be edited into memory. It will not load large files (larger than ~500Kb) which would cause performance issues or cause the app to crash. Please do not raise issues about the **Too large** dialog shown when attempting to load a large file. ![Editor](https://github.com/billthefarmer/billthefarmer.github.io/raw/master/images/Editor.png) ![Editor](https://github.com/billthefarmer/billthefarmer.github.io/raw/master/images/Editor-chooser.png) ![Editor](https://github.com/billthefarmer/billthefarmer.github.io/raw/master/images/Editor-landscape.png) ![Editor](https://github.com/billthefarmer/billthefarmer.github.io/raw/master/images/Editor-syntax.png) This is a fairly simple generic text editor which may be used standalone or to show or edit any sort of text file from another app. If you select a text file in a file manager or similar app you will be offered the option of using this editor along with whatever other apps you have installed that can show or edit a text file. Files will initially be opened read only, long touch on the display or touch the edit item in the toolbar to enable editing. There are five toolbar items which may appear: * **Edit** – Edit the current read only file * **View** – View the current file read only * **Save** – Save the current file if modified * **New** – Start a new empty file * **Open** – Open a text file using a chooser And on the menu: * **Open recent** – Pop up a list of recent files * **Clear list** – Clear list of recent files * **Search** – Interactive search of text using a regular expression * **Find all** – Find all recent files containing search text * **Save as** – Save the current file with a new name * **Go to** – Scroll to selected position in file * **Print** – Print current file * **View markdown** – View markdown in browser or html viewer * **Charset** – Change the current character set, shows current set * **Options** – Select options * **View files** – Open files read only for viewing * **Open last** – Open last opened file on startup * **Auto save** – Save the current file on app pause * **Word wrap** – Limit text width to screen width and word wrap * **Suggestions** – Text input and spelling suggestions * **Highlight syntax** – Highlight programming language syntax * **Theme** – Choose theme * **Light** * **Dark** * **System** * **White** * **Black** * **Retro** * **Text size** – Choose text size * **Small** * **Medium** * **Large** * **Typeface** – Choose typeface * **About** – Show version, copyright and licence ### Edit Edit the current read only text. ### View View the current file read only. ### Save Save the current file if modified. ### New Start a new empty file. Use the **Save as** item to save the new file. ### Open Choose a file to open from the chooser dialog that pops up. The parent folder will be the first in the list. See [File Chooser](Chooser.md). The file will initially be read-only. Touch the **Edit** toolbar item to enable editing. ### Open recent Choose a file from the list that pops up. As above the file will initially be read only. The last entry, **Clear list**, will clear the list. ### Save as Use the dialog and the **Save** button or the **Storage** button to use the android file manager to save the file. ### Search Enter search text in the field that pops up in the toolbar. The first matching item will be highlighted. Use the search button in the keyboard for find next. The exact regular expression syntax used is in the android documentation for [Pattern](https://developer.android.com/reference/java/util/regex/Pattern#sum). Odd text patterns unlikely to be found in an ordinary source file can hang the regex functionality so the app stops working. There is no way to predict or recover from this. ### Find all You may find all recent files that contain the current search text. This menu item will only appear while the search widget is active. A dialog will pop up with a list of matching files. Touch an entry to open that file. You may repeat this or refine the search text to find the desired file. ### Go to Select position in the current file on the horizontal seek bar in the dialog which will pop up. ### Print Print the current file. If you would like the output highlighted, you will need to scroll slowly through the whole file to give the app a chance to highlight it. **Caution** – Attempting to print a large file on an older device with limited resources may cause the app to stop responding. ### View markdown You will be prompted to choose a viewer for an html file containing the encoded markdown from the current open file. If the text contains no markdown the result will be the same text. ### Shortcuts You may create a **New file** or an **Open file** shortcut in the launcher. The **New file** widget will create an shortcut to open a new file in Editor. The **Open file** widget will pop up a dialog showing the file chooser. You may choose a file or use the **Storage** button. You may cancel and fill in the name and path fields, or edit the name or path fields after choosing a file. Use the **Create** button to create the shortcut. **Note** – content URIs returned by the android file picker will not be resolved. ### Regular expressions Explaining [regular expressions](https://en.wikipedia.org/wiki/Regular_expression) used in the text search is beyond the scope of this README. There is at least one [book](https://www.oreilly.com/library/view/mastering-regular-expressions/0596528124/) devoted to the subject. Use `(?i)` for case insensitive search. ### Character set The current character set is displayed under the current file name. The character set is optionally detected when a new file is read. It may be changed by selecting the **Charset** item in the menu, which shows the current character set. See [Character set](Charset.md). ### Typeface The **Typeface** menu item shows a choice of common typefaces. These are aliases for the fonts commonly provided on android devices. Some of them resolve to the same font, depending on the device. ### Highlight syntax If the current open file is a C, C++, Objective C, Go, Dart, Java, Javascript, Python, Shell script, Swift, Rust, CSS, HTML, Org or Markdown file, the keywords, classes comments, strings, etc will be highlighted. See [Syntax Highlighting](Syntax.md). ### Mode line If a line of text is found within the first or last two or three lines of the file which matches the mode line pattern, the mode of the editor will be changed after the file is loaded. See [Mode line](Mode.md). ``` # ed: [[no]vw] [[no]ww] [[no]sg] [[no]hs] [cs:u] [th:l|d|s|w|b|r] [ts:l|m|s] [tf:m|p|s] ``` ### Word count The file word count and character count are shown in the toolbar. Due to the algorithm used, the result may differ from that produced by other utilities. ### Extended selection If the file being edited is not a plain text file, selections created by double tapping or long touching on the text will be extended to enclosing delimiters (brackets, quotes) on the same text line. ### Text size Text size may be changed from the menu or by pinch or expand gestures on the text or by doubletap and swipe. The response to gestures on large files may be slow or delayed. ### Unsaved file If you touch the new, back or open button, and the current file has been modified, you will be prompted whether you want to save it, else the editor will just exit or open a file chooser. The current file may be saved on app pause using the menu option. The scroll position and name will be remembered for the last 10 files opened. ### Changed file If a file has changed in storage while it was open in the editor, if you attempt to save it, or the app is resumed, you will be prompted whether to overwrite or reload the file. ### Default file If there is no open file any text entered will by default be saved in `Documents/Editor.txt`. This file will be loaded on start if it exists. Use the `Save as` menu item to save it elsewhere. ### Shared file Text files opened or shared by another app may be viewed and edited. Some apps may share files or text using a `content` URI that is not resolvable to a path to a file in storage. In that case the editor will read the file into a new file. The **Save** item will save the file in the original location if possible. **Note** – Apps that share files will usually only give another app read permission. Use the **Save as** menu item to save the file elsewhere. ### Keyboard shortcuts When using an external keyboard, some keyboard shortcuts are implemented: * Ctrl+E – Edit mode * Ctrl+Shift+E – View mode * Ctrl+F – Search * Ctrl+Shift+F – Close search * Ctrl+Alt+F – Find next * Ctrl+G – Go to * Ctrl+M – Show menu * Ctrl+N – New file * Ctrl+O – Open file * Ctrl+S – Save file * Ctrl+Shift+S – Save as * Ctrl++ – Increase text size * Ctrl+- – Decrease text size * F3 – Find next * F10 – Show menu Many other shortcuts – Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X, Ctrl+Z are already build in to android. ### SD cards Android allows removable SD cards to be used like a USB stick or as part of the device storage. Files opened using the file chooser on a removable SD card may not save successfully using the save button. Use the **Save as** menu item and the **Storage** button to save it using the android file manager. Alternatively use the **Storage** button on the file chooser dialog to open the file using the android file manager. See [File Chooser](Chooser.md). ================================================ FILE: Syntax.md ================================================ # Syntax Highlighting ## Selection The type of highlighting is selected by file extension. Files with `.c`, `.cc`, `.c++`, `.cxx`, `.m`, `.h`, `.go`, `.js`, `.java`, `.py`, `.sh`, `.swift` extensions will be highlighted with 'C' style highlighting. Files with `.htm`, `.html` extensions will be highlighted as HTML. Files with `.cs`, `.css` extensions will be highlighted as CSS. Files with `.org` extension will be highlighted as Emacs Org. Files with `.md` extensions will be highlighted as markdown. ## Parsing The algorithm makes no attempt at parsing. The text is scanned for relevent keywords, classes, constants, strings and comments and highlighted accordingly. Therefore it will not be exactly correct, but good enough for a simple text editor. See [Source Code Syntax Highlighting][1]. ### C type Keywords and types are matched from lists of C/C++/Objective C/Dart/Go/Java/Javascript/Python/Shell/Swift/Rust keywords and types. Classes are capitalised words. Constants are all caps words. Strings are in double quotes. Single quotes are ignored because apostrophes break the algorithm. Both `/* */` and `// ` C style comments and `# ` Shell script style comments are recognised. ### HTML HTML keywords are matched from a list. Double quoted arguments are highlighted. As above, single quotes are ignored. HTML comments `` are recognised. ### CSS CSS style names are matched from a list. Double quoted arguments are highlighted. As above, single quotes are ignored. C style comments are recognised. ### Emacs Org Metadata, headers, links, emphasis and inline code will be highlighted. ### Markdown Markdown headers, links, emphasis and code will be highlighted. ### Default Files with unrecognised extensions which are not plain text files will be highlighted with default highlighting, similar to C type highlighting. Comments will not be highlighted as there is little consistency with comment delimiters outside C type languages. **Caution** Files with strings of symbols may defeat the regex processing and cause the app to stop responding. ## Limitations Because scanning and highlighting a large file can be quite slow, making the app unresponsive, only the text currently in view is scanned and highlighted. Therefore as the text is edited or scrolled, the new region in view will be scanned and highlighted after a short delay to allow for user typing without the highlighting running constantly. ### Scrolling After the text is highlighted, the android view system will re-layout the views whether they need it or not. That causes the current cursor position to be scrolled back into view, which can be extremely annoying. So the cursor is moved if necessary to keep it within the visible region. ### Horizontal scrolling On devices running android versions less than Marshmallow M (6), horizontal scrolling will scroll back again. Make the text size smaller or rotate the device to avoid this. Or turn the highlighting off. [1]: https://billthefarmer.github.io/blog/post/source-code-highlighting (https://billthefarmer.github.io/blog/post/source-code-highlighting) ================================================ FILE: build.gradle ================================================ buildscript { repositories { mavenCentral() google() } dependencies { classpath 'com.android.tools.build:gradle:8.13.2' } } allprojects { repositories { mavenCentral() google() } tasks.withType(JavaCompile) { options.deprecation = true } } apply plugin: 'com.android.application' android { compileSdkVersion 35 namespace = "org.billthefarmer.editor" defaultConfig { applicationId "org.billthefarmer.editor" minSdkVersion 21 targetSdkVersion 35 versionName "1.97" versionCode 197 buildConfigField "long", "BUILT", System.currentTimeMillis() + "L" } compileOptions { sourceCompatibility JavaVersion.VERSION_1_9 targetCompatibility JavaVersion.VERSION_1_9 } buildFeatures { buildConfig = true } lintOptions { disable 'ScopedStorage', 'OldTargetApi', 'NonConstantResourceId', 'UnusedResources', 'AndroidGradlePluginVersion', 'GradleDependency', 'DiscouragedApi' // abortOnError false } } dependencies { implementation 'org.commonmark:commonmark:0.27.1' } ================================================ FILE: docs/404.html ================================================ Editor Well, a fine little mess. Easy in, easy out. Another triumph. ================================================ FILE: docs/categories/index.xml ================================================ Categories on Editor https://billthefarmer.github.io/editor/categories/ Recent content in Categories on Editor Hugo en-gb Copyright © 2006 Bill Farmer ================================================ FILE: docs/css/custom.css ================================================ table, th, td { border: none; } td { vertical-align: top; padding: 0; } section.page h1, section.page h3 { border: none; padding: 0; } section.page h3 a, section.page h3 a:hover, section.page h3 a:visited { text-decoration: none; } ================================================ FILE: docs/css/styles.css ================================================ html, body { font-family: "Open Sans", sans-serif; color: #363636; height: 100%; } @media (min-width: 48em) { html { font-size: 16px; } } @media (min-width: 58em) { html { font-size: 20px; } } @media (min-width: 48em) { .content { margin-left: 21rem; margin-right: 2rem; } } @media (min-width: 64em) { .content { margin-left: 22rem; margin-right: 3rem; } } /* Sidebar */ .sidebar { overflow: auto; text-align: center; padding: 1rem 1rem; color: white; background-color: #363636; display: flex; flex-direction: column; } .sidebar.sidebar-default { background-color: #363636; } .sidebar.sidebar-green { background-color: #459D61; } .sidebar.sidebar-purple { background-color: #77518A; } .sidebar.sidebar-pink { background-color: #AD6AA9; } .sidebar.sidebar-red { background-color: #B05353; } .sidebar.sidebar-cyan { background-color: #5399B0; } .sidebar.sidebar-blue { background-color: #5378B0; } .sidebar.sidebar-grey { background-color: #959492; } .sidebar.sidebar-orange { background-color: #DAA35C; } @media (min-width: 48em) { .sidebar { position: fixed; top: 0; left: 0; bottom: 0; width: 19rem; text-align: left; } } .site-title { margin-top: 0px; } .sidebar a, .sidebar a:hover, .sidebar a:visited { text-decoration: none; color: white; } .sidebar a:hover { color: rgb(223, 223, 223);; } .sidebar ul { margin: 0px; padding: 0px; } .sidebar ul li { list-style: none; padding-left: 2em; } nav { margin: 1em 0 1em 0; } .sidebar .navigation { flex: 1 0 auto; } .sidebar .version { font-size: 80%; text-align: right; padding: 2px; } .sidebar .external-title { margin-top: 2em; text-align: center; font-size: 120%; } .sidebar nav.external { font-size: 80%; } /* Blocks */ .block { margin: 1em 0em 1em 0em; padding: 0 5px 5px 5px; border-top: 34px solid; position: relative; overflow-wrap: break-word; } .block:before { position: absolute; top: -32px; left: 10px; color: white; } .block.tip { background: #e8f7e6; border-top-color: #84c578; } .block.block.tip:before { content: "Tip"; } .block.note { background: #e6f3fb; border-top-color: #6bb1e0; } .block.block.note:before { content: "Note"; } .block.info { background: #fefaf5; border-top-color: #f1b37e; } .block.block.info:before { content: "Info"; } .block.warn { background: #fbeded; border-top-color: #d58181; } .block.block.warn:before { content: "Warning"; } /* Section of the page */ section.page { margin-bottom: 3em; } section.page h1 { border-left: 3px solid #363636; padding-left: 0.5em; margin-bottom: 0; } section.page .content { margin-left: 0.5em; } section.page h1 a, section.page h1 a:hover, section.page h1 a:visited { text-decoration: none; color: #363636; } section.page a, section.page a:hover, section.page a:visited { color: #363636; } section div pre { overflow: auto; } section code { background-color: #fafafa; } section img { max-width: 100%; } table { border-collapse: collapse; } table,th, td { border: 1px solid black; } td{ padding: 5px; } ================================================ FILE: docs/index.html ================================================ Editor

Introduction

Android simple generic text editor.

Editor Chooser

This is a very simple generic text editor which may be used standalone or to show or edit any sort of text file from another app. If you select a text file in a file manager or similar app you will be offered the option of using this editor along with whatever other apps you have installed that can show or edit a text file. Files will initially be opened read only, long touch on the display or touch the edit item in the toolbar to enable editing.

Features

  • File chooser
  • Default file
  • View markdown in browser or html viewer
  • Regular expression text search
  • Character set detection and selection
  • Optional syntax highlighting
  • Open recent files from menu
  • Optionally view files
  • Optional auto save
  • Optional Word wrap
  • New file shortcut
  • Light/Dark/Black/Retro themes
  • Small/Medium/Large font size
  • Monospace/Proportional/Sans serif/Serif font faces

Using

Toolbar

Toolbar

There are five toolbar items which may appear:

  • Edit – Edit the current read only file
  • View – View the current file read only
  • Save – Save the current file if modified
  • New – Start a new empty file
  • Open – Open a text file using a chooser

And on the menu:

  • Open recent – Pop up a list of recent files
    • Clear list – Clear list of recent files
  • Search – Interactive search of text using a regular expression
  • Find all – Find all recent files containing search text
  • Save as – Save the current file with a new name
  • Go to – Scroll to selected position in file
  • View markdown – View markdown in browser or html viewer
  • Charset – Select character set, shows current set
  • Options – Select options
    • View files – Open files read only for viewing
    • Open last – Open last opened file on startup
    • Auto save – Save the current file on app pause
    • Word wrap – Limit text width to screen width and word wrap
    • Suggestions – Text input and spelling suggestions
    • Highlight syntax – Highlight programming language syntax
  • Theme – Choose theme
    • Light
    • Dark
    • System
    • White
    • Black
    • Retro
  • Text size – Choose text size
    • Small
    • Medium
    • Large
  • Typeface – Choose typeface
    • Monospace
    • Proportional
  • About – Show version, copyright and licence

Open

Choose a file to open from the chooser dialog that pops up. The file will initially be read-only. Touch the Edit toolbar item to enable editing.

The chooser shows a scrollable row of folder buttons and list of files with icons. Files which appear to be media files, or are too large will be disabled and not selectable. Touch a folder button or a folder to change folder, or a file to open a file. Hidden files beginning with a ‘.’ will not appear.

The parent folder, if it exists, will appear first in the list. Touch that folder to move up the directory tree. If a folder is not accessible, the chooser will show the parent folder, if it exists, and the external storage folder (/storage/emulated/0).

Use the Storage button to open files using the android file manager. This should ensure that files on removeable SD cards can be saved using the Save button. The file manager may refuse to open some types of text files not recognised by android.

Open Recent

Choose a file from the list that pops up. As above the file will initially be read only. The last entry, Clear list, will clear the list.

Save As

Enter a new file name in the dialog that pops up. Absolute names starting with a slash ‘/’ will be saved in that exact path. Names without a starting slash will be saved relative to the main public folder, /sdcard/, or /storage/emulated/0/. Touch the Storage button to use the android file manager to save the file.

Findall

FindAll

You may find all recent files that contain the current search text. This menu item will only appear while the search widget is active. A dialog will pop up with a list of matching files. Touch an entry to open that file. You may repeat this or refine the search text to find the desired file.

Go to

Go to

Select position in the current file on the horizontal seek bar in the dialog which will pop up.

Print

Print

Print the current file. If you would like the output highlighted, you will need to scroll slowly through the whole file to give the app a chance to highlight it. Caution – Attempting to print a large file on an older device with limited resources may cause the app to stop responding.

View Markdown

You will be prompted to choose a viewer for an html file containing the encoded markdown from the current open file. If the text contains no markdown the result will be the same text.

Character set

Charset

The current character set is displayed under the current file name. The character set is detected when a new file is read. It may be changed by selecting the Charset item in the menu, which shows the current character set.

Default

The default character set is set to UTF-8 on selecting New from the toolbar. It may be changed in the menu. Android defaults to UTF-8, don’t use anything else unless you are sure what you are doing.

Detection

The current character set is detected on reading a file by the detection code from International Components for Unicode. If there are no accented characters or symbols in the text to give the detection algorithm something to work on it may not get it right.

Saving

Files will be saved using the current character set. To change it, use the Charset item in the menu, which shows the current set.

Caution – If you add accented characters or symbols to the text, make sure to check the current character set before you save it.

Use mode line

The character set may be set to UTF-8 by using a mode line in the text.

# ed: cs:u

See Mode Line

Typeface

Typeface

The Typeface menu item shows a choice of common typefaces. These are aliases for the fonts commonly provided on android devices. Some of them resolve to the same font, depending on the device.

Regular Expressions

Explaining regular expressions used in the text search is beyond the scope of these docs. There is at least one book (of many) devoted to the subject. Use (?i) for case insensitive search, . matches any character once, .? matches any character once or not at all, .+ matches any character one or more times, .* matches any character any times or not at all. Use .+? or .*? for reluctant versions. Use \b for a word boundary, \d for a digit, \s for a white space character, \w for a word character, so \w+ matches words. Use [abc] to match a set of characters, or [a-z] for a range, so \w*[aeiou]+\w* should match any word with at least one vowel in it.

Shortcuts

Shortcut Shortcut

Shortcut Shortcut

You may create a New file or an Open file shortcut in the launcher. The New file widget will create an shortcut to open a new file in Editor. The Open file widget will pop up a dialog showing the file chooser. You may choose a file or use the Storage button. You may cancel and fill in the name and path fields, or edit the name or path fields after choosing a file. Use the Create button to create the shortcut. Note – content URIs returned by the android file picker will not be resolved.

Highlight Syntax

Syntax

If the current open file is a C, C++, Objective C, Dart, Go, Java, Javascript, Python, Rust, Shell script, Swift, CSS, HTML, Emacs Org or Markdown file, the keywords, classes comments, strings, etc will be highlighted.

Selection

The type of highlighting is selected by file extension. Files with .c, .cc, .c++, .cxx, .m, .h, .dart, .go, .js, .java, .py, .rs, .sh, .swift extensions will be highlighted with ‘C’ style highlighting. Files with .htm, .html extensions will be highlighted as HTML. Files with .cs, .css extensions will be highlighted as CSS. Files with .md extensions will be highlighted as markdown. Files with .org extensions will be highlighted as Emacs Org.

Parsing

The algorithm makes no attempt at parsing. The text is scanned for relevent keywords, classes, constants, strings and comments and highlighted accordingly. Therefore it will not be exactly correct, but good enough for a simple text editor. See Source Code Syntax Highlighting.

C type

Keywords and types are matched from lists of C/C++/Objective C/Go/Java/Javascript/Python/Shell/Swift keywords and types. Classes are capitalised words. Constants are all caps words. Strings are in double quotes. Single quotes are ignored because apostrophes break the algorithm. Both /* */ and // C style comments and # Shell script style comments are recognised.

HTML

HTML keywords are matched from a list. Double quoted arguments are highlighted. As above, single quotes are ignored. HTML comments <!-- --> are recognised.

CSS

CSS style names are matched from a list. Double quoted arguments are highlighted. As above, single quotes are ignored. C style comments are recognised.

Markdown

Markdown headers, links, emphasis and code will be highlighted.

Emacs Org

Metadata, headers, links, emphasis and inline code will be highlighted.

Default

Files with unrecognised extensions which are not plain text files will be highlighted with default highlighting, similar to C type highlighting. Comments will not be highlighted as there is little consistency with comment delimiters outside C type languages.

Caution Files with strings of symbols may defeat the regex processing and cause the app to stop responding.

Limitations

Because scanning and highlighting a large file can be quite slow, making the app unresponsive, only the text currently in view is scanned and highlighted. Therefore as the text is edited or scrolled, the new region in view will be scanned and highlighted after a short delay to allow for user typing without the highlighting running constantly.

Scrolling

After the text is highlighted, the android view system will re-layout the views whether they need it or not. That causes the current cursor position to be scrolled back into view, which can be extremely annoying. So the cursor is moved if necessary to keep it within the visible region.

Horizontal scrolling

On devices running android versions less than Marshmallow M (6), horizontal scrolling will scroll back again. Make the text size smaller or rotate the device to avoid this. Or turn the highlighting off.

Mode Line

If a line of text is found within the first or last two or three lines of the file which matches the mode line pattern, the mode of the editor will be changed after the file is loaded. The pattern is one or more text or punctuation characters, white space, the text ed: followed by one or more option patterns separated by white space.

# ed: [[no]vw] [[no]ww] [[no]sg] [[no]hs] [cs:u] [th:l|d|s|w|b|r] [ts:l|m|s] [tf:m|p|s]

The initial text or punctuation characters are intended to be used to hide the mode line from compilers and interpreters by commenting it out.

The option patterns are:

  • [no]vw – View files read only
  • [no]ww – Word wrap
  • [no]sg – Suggestions
  • [no]hs – Syntax highlighting
  • cs:u – Character set – UTF-8
  • th:l|d|s|w|b|r – Theme – light, dark, system, white, black or retro
  • ts:l|m|s – Text size – large, medium or small
  • tf:m|p|s – Typeface – monospace, proportional (sans) or serif

The mode line is read after the file is loaded and will change immediately, except in Android 6, Marshmallow due to an obscure bug. Rotate the device to change mode.

Word Count

The file word count and character count are shown in the toolbar. Due to the algorithm used, the result may differ from that produced by other utilities.

Extended Selection

If the file being edited is not a plain text file, selections created by double tapping or long touching on the text will be extended to enclosing delimiters (brackets, quotes) on the same text line.

Text Size

Text size may be changed from the menu or by pinch or expand gestures on the text or by doubletap and swipe. The response to gestures on large files may be slow or delayed.

Unsaved File

If you touch the new, back or open button, and the current file has been modified, you will be prompted whether you want to save it, else the editor will just exit or open a file chooser. The current file may be saved on app pause using the menu option. The scroll position and name will be remembered for the last 10 files opened.

Changed File

If a file has changed in storage while it was open in the editor, if you attempt to save it, or the app is resumed, you will be prompted whether to overwrite or reload the file.

Default File

If there is no open file any text entered will by default be saved in Documents/Editor.txt. This file will be loaded on start if it exists. Use the Save as menu item to save it elsewhere.

Shared File

Text files opened or shared by another app may be viewed and edited. Some apps may share files or text using a content URI that is not resolvable to a path to a file in storage. In that case the editor will read the file into a new file. The Save item will save the file in the original location if possible.

Note – Apps that share files will usually only give another app read permission. Use the Save as menu item to save the file elsewhere.

Keyboard Shortcuts

When using an external keyboard, some keyboard shortcuts are implemented:

  • Ctrl+E – Edit mode
  • Ctrl+Shift+E – View mode
  • Ctrl+F – Search
  • Ctrl+Shift+F – Close search
  • Ctrl+Alt+F – Find next
  • Ctrl+G – Go to
  • Ctrl+M – Show menu
  • Ctrl+N – New file
  • Ctrl+O – Open file
  • Ctrl+S – Save file
  • Ctrl+Shift+S – Save as
  • Ctrl++ – Increase text size
  • Ctrl+- – Decrease text size
  • F3 – Find next
  • F10 – Show menu

Many other shortcuts – Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X, Ctrl+Z are already build in to android.

================================================ FILE: docs/index.xml ================================================ Editor https://billthefarmer.github.io/editor/ Recent content on Editor Hugo en-gb Copyright &copy; 2006 Bill Farmer Sun, 18 Feb 2024 10:54:01 +0000 Features https://billthefarmer.github.io/editor/introduction/features/ Wed, 04 Mar 2020 15:40:25 +0000 https://billthefarmer.github.io/editor/introduction/features/ <ul> <li>File chooser</li> <li>Default file</li> <li>View markdown in browser or html viewer</li> <li>Regular expression text search</li> <li>Character set detection and selection</li> <li>Optional syntax highlighting</li> <li>Open recent files from menu</li> <li>Optionally view files</li> <li>Optional auto save</li> <li>Optional Word wrap</li> <li>New file shortcut</li> <li>Light/Dark/Black/Retro themes</li> <li>Small/Medium/Large font size</li> <li>Monospace/Proportional/Sans serif/Serif font faces</li> </ul> Toolbar https://billthefarmer.github.io/editor/using/toolbar/ Wed, 04 Mar 2020 16:06:10 +0000 https://billthefarmer.github.io/editor/using/toolbar/ <p>There are five toolbar items which may appear:</p> <ul> <li><strong>Edit</strong> – Edit the current read only file</li> <li><strong>View</strong> – View the current file read only</li> <li><strong>Save</strong> – Save the current file if modified</li> <li><strong>New</strong> – Start a new empty file</li> <li><strong>Open</strong> – Open a text file using a chooser</li> </ul> <p>And on the menu:</p> <ul> <li><strong>Open recent</strong> – Pop up a list of recent files <ul> <li><strong>Clear list</strong> – Clear list of recent files</li> </ul> </li> <li><strong>Search</strong> – Interactive search of text using a regular expression</li> <li><strong>Find all</strong> – Find all recent files containing search text</li> <li><strong>Save as</strong> – Save the current file with a new name</li> <li><strong>Go to</strong> – Scroll to selected position in file</li> <li><strong>View markdown</strong> – View markdown in browser or html viewer</li> <li><strong>Charset</strong> – Select character set, shows current set</li> <li><strong>Options</strong> – Select options <ul> <li><strong>View files</strong> – Open files read only for viewing</li> <li><strong>Open last</strong> – Open last opened file on startup</li> <li><strong>Auto save</strong> – Save the current file on app pause</li> <li><strong>Word wrap</strong> – Limit text width to screen width and word wrap</li> <li><strong>Suggestions</strong> – Text input and spelling suggestions</li> <li><strong>Highlight syntax</strong> – Highlight programming language syntax</li> </ul> </li> <li><strong>Theme</strong> – Choose theme <ul> <li><strong>Light</strong></li> <li><strong>Dark</strong></li> <li><strong>System</strong></li> <li><strong>White</strong></li> <li><strong>Black</strong></li> <li><strong>Retro</strong></li> </ul> </li> <li><strong>Text size</strong> – Choose text size <ul> <li><strong>Small</strong></li> <li><strong>Medium</strong></li> <li><strong>Large</strong></li> </ul> </li> <li><strong>Typeface</strong> – Choose typeface <ul> <li><strong>Monospace</strong></li> <li><strong>Proportional</strong></li> </ul> </li> <li><strong>About</strong> – Show version, copyright and licence</li> </ul> Open https://billthefarmer.github.io/editor/using/open/ Wed, 04 Mar 2020 19:32:49 +0000 https://billthefarmer.github.io/editor/using/open/ <p>Choose a file to open from the chooser dialog that pops up. The file will initially be read-only. Touch the Edit toolbar item to enable editing.</p> <p>The chooser shows a scrollable row of folder buttons and list of files with icons. Files which appear to be media files, or are too large will be disabled and not selectable. Touch a folder button or a folder to change folder, or a file to open a file. Hidden files beginning with a &lsquo;.&rsquo; will not appear.</p> Open Recent https://billthefarmer.github.io/editor/using/open-recent/ Wed, 04 Mar 2020 19:32:37 +0000 https://billthefarmer.github.io/editor/using/open-recent/ <p>Choose a file from the list that pops up. As above the file will initially be read only. The last entry, <strong>Clear list</strong>, will clear the list.</p> Save As https://billthefarmer.github.io/editor/using/save-as/ Wed, 04 Mar 2020 19:33:09 +0000 https://billthefarmer.github.io/editor/using/save-as/ <p>Enter a new file name in the dialog that pops up. Absolute names starting with a slash &lsquo;/&rsquo; will be saved in that exact path. Names without a starting slash will be saved relative to the main public folder, <code>/sdcard/</code>, or <code>/storage/emulated/0/</code>. Touch the <strong>Storage</strong> button to use the android file manager to save the file.</p> Search https://billthefarmer.github.io/editor/using/search/ Wed, 04 Mar 2020 19:38:08 +0000 https://billthefarmer.github.io/editor/using/search/ <p><img src="images/Editor-search.png" alt="Search"></p> <p>Enter search text in the field that pops up in the toolbar. The first matching item will be highlighted. Use the search button in the keyboard for find next. The exact regular expression syntax used is in the android documentation for <a href="https://developer.android.com/reference/java/util/regex/Pattern#sum">Pattern</a>.</p> Findall https://billthefarmer.github.io/editor/using/findall/ Thu, 26 Mar 2020 09:56:27 +0000 https://billthefarmer.github.io/editor/using/findall/ <p><img src="images/Editor-findall.png" alt="FindAll"></p> <p>You may find all recent files that contain the current search text. This menu item will only appear while the search widget is active. A dialog will pop up with a list of matching files. Touch an entry to open that file. You may repeat this or refine the search text to find the desired file.</p> Go to https://billthefarmer.github.io/editor/using/goto/ Thu, 17 Nov 2022 09:49:16 +0000 https://billthefarmer.github.io/editor/using/goto/ <p><img src="images/Editor-goto.png" alt="Go to"></p> <p>Select position in the current file on the horizontal seek bar in the dialog which will pop up.</p> Print https://billthefarmer.github.io/editor/using/print/ Sat, 26 Nov 2022 09:54:15 +0000 https://billthefarmer.github.io/editor/using/print/ <p><img src="images/Editor-print.png" alt="Print"></p> <p>Print the current file. If you would like the output highlighted, you will need to scroll slowly through the whole file to give the app a chance to highlight it. <strong>Caution</strong> – Attempting to print a large file on an older device with limited resources may cause the app to stop responding.</p> View Markdown https://billthefarmer.github.io/editor/using/view-markdown/ Wed, 04 Mar 2020 19:40:02 +0000 https://billthefarmer.github.io/editor/using/view-markdown/ <p>You will be prompted to choose a viewer for an html file containing the encoded markdown from the current open file. If the text contains no markdown the result will be the same text.</p> Character set https://billthefarmer.github.io/editor/using/charset/ Wed, 03 Nov 2021 21:12:12 +0000 https://billthefarmer.github.io/editor/using/charset/ <p><img src="images/Editor-charset.png" alt="Charset"></p> <p>The current character set is displayed under the current file name. The character set is detected when a new file is read. It may be changed by selecting the Charset item in the menu, which shows the current character set.</p> <h4 id="default">Default</h4> <p>The default character set is set to UTF-8 on selecting New from the toolbar. It may be changed in the menu. Android defaults to UTF-8, don&rsquo;t use anything else unless you are sure what you are doing.</p> Typeface https://billthefarmer.github.io/editor/using/typeface/ Sun, 18 Feb 2024 10:54:01 +0000 https://billthefarmer.github.io/editor/using/typeface/ <p><img src="images/Editor-typeface.png" alt="Typeface"></p> <p>The <strong>Typeface</strong> menu item shows a choice of common typefaces. These are aliases for the fonts commonly provided on android devices. Some of them resolve to the same font, depending on the device.</p> Regular Expressions https://billthefarmer.github.io/editor/using/regular-expressions/ Sun, 05 Sep 2021 09:48:08 +0100 https://billthefarmer.github.io/editor/using/regular-expressions/ <p>Explaining <a href="https://en.wikipedia.org/wiki/Regular_expression">regular expressions</a> used in the text search is beyond the scope of these docs. There is at least one <a href="https://www.oreilly.com/library/view/mastering-regular-expressions/0596528124/">book</a> (of many) devoted to the subject. Use <code>(?i)</code> for case insensitive search, <code>.</code> matches any character once, <code>.?</code> matches any character once or not at all, <code>.+</code> matches any character one or more times, <code>.*</code> matches any character any times or not at all. Use <code>.+?</code> or <code>.*?</code> for reluctant versions. Use <code>\b</code> for a word boundary, <code>\d</code> for a digit, <code>\s</code> for a white space character, <code>\w</code> for a word character, so <code>\w+</code> matches words. Use <code>[abc]</code> to match a set of characters, or <code>[a-z]</code> for a range, so <code>\w*[aeiou]+\w*</code> should match any word with at least one vowel in it.</p> Shortcuts https://billthefarmer.github.io/editor/using/shortcut/ Wed, 02 Mar 2022 09:34:09 +0000 https://billthefarmer.github.io/editor/using/shortcut/ <p><img src="images/Editor-widgets.png" alt="Shortcut"> <img src="images/Editor-shortcut.png" alt="Shortcut"></p> <p><img src="images/Editor-open.png" alt="Shortcut"> <img src="images/Editor-name.png" alt="Shortcut"></p> <p>You may create a <strong>New file</strong> or an <strong>Open file</strong> shortcut in the launcher. The <strong>New file</strong> widget will create an shortcut to open a new file in Editor. The <strong>Open file</strong> widget will pop up a dialog showing the file chooser. You may choose a file or use the <strong>Storage</strong> button. You may cancel and fill in the name and path fields, or edit the name or path fields after choosing a file. Use the <strong>Create</strong> button to create the shortcut. <strong>Note</strong> – content URIs returned by the android file picker will not be resolved.</p> Highlight Syntax https://billthefarmer.github.io/editor/using/highlight-syntax/ Wed, 04 Mar 2020 19:41:14 +0000 https://billthefarmer.github.io/editor/using/highlight-syntax/ <p><img src="images/Editor-syntax.png" alt="Syntax"></p> <p>If the current open file is a C, C++, Objective C, Dart, Go, Java, Javascript, Python, Rust, Shell script, Swift, CSS, HTML, <a href="https://orgmode.org" title="https://orgmode.org">Emacs Org</a> or Markdown file, the keywords, classes comments, strings, etc will be highlighted.</p> <h3 id="selection">Selection</h3> <p>The type of highlighting is selected by file extension. Files with <code>.c</code>, <code>.cc</code>, <code>.c++</code>, <code>.cxx</code>, <code>.m</code>, <code>.h</code>, <code>.dart</code>, <code>.go</code>, <code>.js</code>, <code>.java</code>, <code>.py</code>, <code>.rs</code>, <code>.sh</code>, <code>.swift</code> extensions will be highlighted with &lsquo;C&rsquo; style highlighting. Files with <code>.htm</code>, <code>.html</code> extensions will be highlighted as HTML. Files with <code>.cs</code>, <code>.css</code> extensions will be highlighted as CSS. Files with <code>.md</code> extensions will be highlighted as markdown. Files with <code>.org</code> extensions will be highlighted as Emacs Org.</p> Mode Line https://billthefarmer.github.io/editor/using/mode-line/ Wed, 04 Mar 2020 17:41:40 +0000 https://billthefarmer.github.io/editor/using/mode-line/ <p>If a line of text is found within the first or last two or three lines of the file which matches the mode line pattern, the mode of the editor will be changed after the file is loaded. The pattern is one or more text or punctuation characters, white space, the text <code>ed:</code> followed by one or more option patterns separated by white space.</p> <pre><code># ed: [[no]vw] [[no]ww] [[no]sg] [[no]hs] [cs:u] [th:l|d|s|w|b|r] [ts:l|m|s] [tf:m|p|s] </code></pre> <p>The initial text or punctuation characters are intended to be used to hide the mode line from compilers and interpreters by commenting it out.</p> Word Count https://billthefarmer.github.io/editor/using/word-count/ Mon, 29 Mar 2021 18:47:58 +0100 https://billthefarmer.github.io/editor/using/word-count/ <p>The file word count and character count are shown in the toolbar. Due to the algorithm used, the result may differ from that produced by other utilities.</p> Extended Selection https://billthefarmer.github.io/editor/using/extended-selection/ Wed, 04 Mar 2020 17:42:02 +0000 https://billthefarmer.github.io/editor/using/extended-selection/ <p>If the file being edited is not a plain text file, selections created by double tapping or long touching on the text will be extended to enclosing delimiters (brackets, quotes) on the same text line.</p> Text Size https://billthefarmer.github.io/editor/using/text-size/ Fri, 16 Jul 2021 09:14:58 +0100 https://billthefarmer.github.io/editor/using/text-size/ <p>Text size may be changed from the menu or by pinch or expand gestures on the text or by doubletap and swipe. The response to gestures on large files may be slow or delayed.</p> Unsaved File https://billthefarmer.github.io/editor/using/unsaved-file/ Wed, 04 Mar 2020 17:42:32 +0000 https://billthefarmer.github.io/editor/using/unsaved-file/ <p>If you touch the new, back or open button, and the current file has been modified, you will be prompted whether you want to save it, else the editor will just exit or open a file chooser. The current file may be saved on app pause using the menu option. The scroll position and name will be remembered for the last 10 files opened.</p> Changed File https://billthefarmer.github.io/editor/using/changed-file/ Wed, 04 Mar 2020 17:42:49 +0000 https://billthefarmer.github.io/editor/using/changed-file/ <p>If a file has changed in storage while it was open in the editor, if you attempt to save it, or the app is resumed, you will be prompted whether to overwrite or reload the file.</p> Default File https://billthefarmer.github.io/editor/using/default-file/ Wed, 04 Mar 2020 17:43:09 +0000 https://billthefarmer.github.io/editor/using/default-file/ <p>If there is no open file any text entered will by default be saved in <code>Documents/Editor.txt</code>. This file will be loaded on start if it exists. Use the <strong>Save as</strong> menu item to save it elsewhere.</p> Shared File https://billthefarmer.github.io/editor/using/shared-file/ Wed, 04 Mar 2020 17:43:39 +0000 https://billthefarmer.github.io/editor/using/shared-file/ <p>Text files opened or shared by another app may be viewed and edited. Some apps may share files or text using a <code>content</code> URI that is not resolvable to a path to a file in storage. In that case the editor will read the file into a new file. The <strong>Save</strong> item will save the file in the original location if possible.</p> <p><strong>Note</strong> – Apps that share files will usually only give another app read permission. Use the <strong>Save as</strong> menu item to save the file elsewhere.</p> Keyboard Shortcuts https://billthefarmer.github.io/editor/using/keyboard-shortcuts/ Wed, 21 Jul 2021 19:22:29 +0100 https://billthefarmer.github.io/editor/using/keyboard-shortcuts/ <p>When using an external keyboard, some keyboard shortcuts are implemented:</p> <ul> <li>Ctrl+E – Edit mode</li> <li>Ctrl+Shift+E – View mode</li> <li>Ctrl+F – Search</li> <li>Ctrl+Shift+F – Close search</li> <li>Ctrl+Alt+F – Find next</li> <li>Ctrl+G – Go to</li> <li>Ctrl+M – Show menu</li> <li>Ctrl+N – New file</li> <li>Ctrl+O – Open file</li> <li>Ctrl+S – Save file</li> <li>Ctrl+Shift+S – Save as</li> <li>Ctrl++ – Increase text size</li> <li>Ctrl+- – Decrease text size</li> <li>F3 – Find next</li> <li>F10 – Show menu</li> </ul> <p>Many other shortcuts – Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X, Ctrl+Z are already build in to android.</p> ================================================ FILE: docs/introduction/index.xml ================================================ Introduction on Editor https://billthefarmer.github.io/editor/introduction/ Recent content in Introduction on Editor Hugo en-gb Copyright &copy; 2006 Bill Farmer Wed, 04 Mar 2020 15:40:25 +0000 Features https://billthefarmer.github.io/editor/introduction/features/ Wed, 04 Mar 2020 15:40:25 +0000 https://billthefarmer.github.io/editor/introduction/features/ <ul> <li>File chooser</li> <li>Default file</li> <li>View markdown in browser or html viewer</li> <li>Regular expression text search</li> <li>Character set detection and selection</li> <li>Optional syntax highlighting</li> <li>Open recent files from menu</li> <li>Optionally view files</li> <li>Optional auto save</li> <li>Optional Word wrap</li> <li>New file shortcut</li> <li>Light/Dark/Black/Retro themes</li> <li>Small/Medium/Large font size</li> <li>Monospace/Proportional/Sans serif/Serif font faces</li> </ul> ================================================ FILE: docs/sitemap.xml ================================================ https://billthefarmer.github.io/editor/introduction/ 2020-03-04T15:38:25+00:00 https://billthefarmer.github.io/editor/introduction/features/ 2020-03-04T15:40:25+00:00 https://billthefarmer.github.io/editor/using/ 2020-03-04T16:05:59+00:00 https://billthefarmer.github.io/editor/using/toolbar/ 2020-03-04T16:06:10+00:00 https://billthefarmer.github.io/editor/using/open/ 2020-03-04T19:32:49+00:00 https://billthefarmer.github.io/editor/using/open-recent/ 2020-03-04T19:32:37+00:00 https://billthefarmer.github.io/editor/using/save-as/ 2020-03-04T19:33:09+00:00 https://billthefarmer.github.io/editor/using/search/ 2020-03-04T19:38:08+00:00 https://billthefarmer.github.io/editor/using/findall/ 2020-03-26T09:56:27+00:00 https://billthefarmer.github.io/editor/using/goto/ 2022-11-17T09:49:16+00:00 https://billthefarmer.github.io/editor/using/print/ 2022-11-26T09:54:15+00:00 https://billthefarmer.github.io/editor/using/view-markdown/ 2020-03-04T19:40:02+00:00 https://billthefarmer.github.io/editor/using/charset/ 2021-11-03T21:12:12+00:00 https://billthefarmer.github.io/editor/using/typeface/ 2024-02-18T10:54:01+00:00 https://billthefarmer.github.io/editor/using/regular-expressions/ 2021-09-05T09:48:08+01:00 https://billthefarmer.github.io/editor/using/shortcut/ 2022-03-02T09:34:09+00:00 https://billthefarmer.github.io/editor/using/highlight-syntax/ 2020-03-04T19:41:14+00:00 https://billthefarmer.github.io/editor/using/mode-line/ 2020-03-04T17:41:40+00:00 https://billthefarmer.github.io/editor/using/word-count/ 2021-03-29T18:47:58+01:00 https://billthefarmer.github.io/editor/using/extended-selection/ 2020-03-04T17:42:02+00:00 https://billthefarmer.github.io/editor/using/text-size/ 2021-07-16T09:14:58+01:00 https://billthefarmer.github.io/editor/using/unsaved-file/ 2020-03-04T17:42:32+00:00 https://billthefarmer.github.io/editor/using/changed-file/ 2020-03-04T17:42:49+00:00 https://billthefarmer.github.io/editor/using/default-file/ 2020-03-04T17:43:09+00:00 https://billthefarmer.github.io/editor/using/shared-file/ 2020-03-04T17:43:39+00:00 https://billthefarmer.github.io/editor/using/keyboard-shortcuts/ 2021-07-21T19:22:29+01:00 https://billthefarmer.github.io/editor/ 2024-02-18T10:54:01+00:00 https://billthefarmer.github.io/editor/categories/ https://billthefarmer.github.io/editor/tags/ ================================================ FILE: docs/tags/index.xml ================================================ Tags on Editor https://billthefarmer.github.io/editor/tags/ Recent content in Tags on Editor Hugo en-gb Copyright &copy; 2006 Bill Farmer ================================================ FILE: docs/using/index.xml ================================================ Using on Editor https://billthefarmer.github.io/editor/using/ Recent content in Using on Editor Hugo en-gb Copyright &copy; 2006 Bill Farmer Sun, 18 Feb 2024 10:54:01 +0000 Toolbar https://billthefarmer.github.io/editor/using/toolbar/ Wed, 04 Mar 2020 16:06:10 +0000 https://billthefarmer.github.io/editor/using/toolbar/ <p>There are five toolbar items which may appear:</p> <ul> <li><strong>Edit</strong> – Edit the current read only file</li> <li><strong>View</strong> – View the current file read only</li> <li><strong>Save</strong> – Save the current file if modified</li> <li><strong>New</strong> – Start a new empty file</li> <li><strong>Open</strong> – Open a text file using a chooser</li> </ul> <p>And on the menu:</p> <ul> <li><strong>Open recent</strong> – Pop up a list of recent files <ul> <li><strong>Clear list</strong> – Clear list of recent files</li> </ul> </li> <li><strong>Search</strong> – Interactive search of text using a regular expression</li> <li><strong>Find all</strong> – Find all recent files containing search text</li> <li><strong>Save as</strong> – Save the current file with a new name</li> <li><strong>Go to</strong> – Scroll to selected position in file</li> <li><strong>View markdown</strong> – View markdown in browser or html viewer</li> <li><strong>Charset</strong> – Select character set, shows current set</li> <li><strong>Options</strong> – Select options <ul> <li><strong>View files</strong> – Open files read only for viewing</li> <li><strong>Open last</strong> – Open last opened file on startup</li> <li><strong>Auto save</strong> – Save the current file on app pause</li> <li><strong>Word wrap</strong> – Limit text width to screen width and word wrap</li> <li><strong>Suggestions</strong> – Text input and spelling suggestions</li> <li><strong>Highlight syntax</strong> – Highlight programming language syntax</li> </ul> </li> <li><strong>Theme</strong> – Choose theme <ul> <li><strong>Light</strong></li> <li><strong>Dark</strong></li> <li><strong>System</strong></li> <li><strong>White</strong></li> <li><strong>Black</strong></li> <li><strong>Retro</strong></li> </ul> </li> <li><strong>Text size</strong> – Choose text size <ul> <li><strong>Small</strong></li> <li><strong>Medium</strong></li> <li><strong>Large</strong></li> </ul> </li> <li><strong>Typeface</strong> – Choose typeface <ul> <li><strong>Monospace</strong></li> <li><strong>Proportional</strong></li> </ul> </li> <li><strong>About</strong> – Show version, copyright and licence</li> </ul> Open https://billthefarmer.github.io/editor/using/open/ Wed, 04 Mar 2020 19:32:49 +0000 https://billthefarmer.github.io/editor/using/open/ <p>Choose a file to open from the chooser dialog that pops up. The file will initially be read-only. Touch the Edit toolbar item to enable editing.</p> <p>The chooser shows a scrollable row of folder buttons and list of files with icons. Files which appear to be media files, or are too large will be disabled and not selectable. Touch a folder button or a folder to change folder, or a file to open a file. Hidden files beginning with a &lsquo;.&rsquo; will not appear.</p> Open Recent https://billthefarmer.github.io/editor/using/open-recent/ Wed, 04 Mar 2020 19:32:37 +0000 https://billthefarmer.github.io/editor/using/open-recent/ <p>Choose a file from the list that pops up. As above the file will initially be read only. The last entry, <strong>Clear list</strong>, will clear the list.</p> Save As https://billthefarmer.github.io/editor/using/save-as/ Wed, 04 Mar 2020 19:33:09 +0000 https://billthefarmer.github.io/editor/using/save-as/ <p>Enter a new file name in the dialog that pops up. Absolute names starting with a slash &lsquo;/&rsquo; will be saved in that exact path. Names without a starting slash will be saved relative to the main public folder, <code>/sdcard/</code>, or <code>/storage/emulated/0/</code>. Touch the <strong>Storage</strong> button to use the android file manager to save the file.</p> Search https://billthefarmer.github.io/editor/using/search/ Wed, 04 Mar 2020 19:38:08 +0000 https://billthefarmer.github.io/editor/using/search/ <p><img src="images/Editor-search.png" alt="Search"></p> <p>Enter search text in the field that pops up in the toolbar. The first matching item will be highlighted. Use the search button in the keyboard for find next. The exact regular expression syntax used is in the android documentation for <a href="https://developer.android.com/reference/java/util/regex/Pattern#sum">Pattern</a>.</p> Findall https://billthefarmer.github.io/editor/using/findall/ Thu, 26 Mar 2020 09:56:27 +0000 https://billthefarmer.github.io/editor/using/findall/ <p><img src="images/Editor-findall.png" alt="FindAll"></p> <p>You may find all recent files that contain the current search text. This menu item will only appear while the search widget is active. A dialog will pop up with a list of matching files. Touch an entry to open that file. You may repeat this or refine the search text to find the desired file.</p> Go to https://billthefarmer.github.io/editor/using/goto/ Thu, 17 Nov 2022 09:49:16 +0000 https://billthefarmer.github.io/editor/using/goto/ <p><img src="images/Editor-goto.png" alt="Go to"></p> <p>Select position in the current file on the horizontal seek bar in the dialog which will pop up.</p> Print https://billthefarmer.github.io/editor/using/print/ Sat, 26 Nov 2022 09:54:15 +0000 https://billthefarmer.github.io/editor/using/print/ <p><img src="images/Editor-print.png" alt="Print"></p> <p>Print the current file. If you would like the output highlighted, you will need to scroll slowly through the whole file to give the app a chance to highlight it. <strong>Caution</strong> – Attempting to print a large file on an older device with limited resources may cause the app to stop responding.</p> View Markdown https://billthefarmer.github.io/editor/using/view-markdown/ Wed, 04 Mar 2020 19:40:02 +0000 https://billthefarmer.github.io/editor/using/view-markdown/ <p>You will be prompted to choose a viewer for an html file containing the encoded markdown from the current open file. If the text contains no markdown the result will be the same text.</p> Character set https://billthefarmer.github.io/editor/using/charset/ Wed, 03 Nov 2021 21:12:12 +0000 https://billthefarmer.github.io/editor/using/charset/ <p><img src="images/Editor-charset.png" alt="Charset"></p> <p>The current character set is displayed under the current file name. The character set is detected when a new file is read. It may be changed by selecting the Charset item in the menu, which shows the current character set.</p> <h4 id="default">Default</h4> <p>The default character set is set to UTF-8 on selecting New from the toolbar. It may be changed in the menu. Android defaults to UTF-8, don&rsquo;t use anything else unless you are sure what you are doing.</p> Typeface https://billthefarmer.github.io/editor/using/typeface/ Sun, 18 Feb 2024 10:54:01 +0000 https://billthefarmer.github.io/editor/using/typeface/ <p><img src="images/Editor-typeface.png" alt="Typeface"></p> <p>The <strong>Typeface</strong> menu item shows a choice of common typefaces. These are aliases for the fonts commonly provided on android devices. Some of them resolve to the same font, depending on the device.</p> Regular Expressions https://billthefarmer.github.io/editor/using/regular-expressions/ Sun, 05 Sep 2021 09:48:08 +0100 https://billthefarmer.github.io/editor/using/regular-expressions/ <p>Explaining <a href="https://en.wikipedia.org/wiki/Regular_expression">regular expressions</a> used in the text search is beyond the scope of these docs. There is at least one <a href="https://www.oreilly.com/library/view/mastering-regular-expressions/0596528124/">book</a> (of many) devoted to the subject. Use <code>(?i)</code> for case insensitive search, <code>.</code> matches any character once, <code>.?</code> matches any character once or not at all, <code>.+</code> matches any character one or more times, <code>.*</code> matches any character any times or not at all. Use <code>.+?</code> or <code>.*?</code> for reluctant versions. Use <code>\b</code> for a word boundary, <code>\d</code> for a digit, <code>\s</code> for a white space character, <code>\w</code> for a word character, so <code>\w+</code> matches words. Use <code>[abc]</code> to match a set of characters, or <code>[a-z]</code> for a range, so <code>\w*[aeiou]+\w*</code> should match any word with at least one vowel in it.</p> Shortcuts https://billthefarmer.github.io/editor/using/shortcut/ Wed, 02 Mar 2022 09:34:09 +0000 https://billthefarmer.github.io/editor/using/shortcut/ <p><img src="images/Editor-widgets.png" alt="Shortcut"> <img src="images/Editor-shortcut.png" alt="Shortcut"></p> <p><img src="images/Editor-open.png" alt="Shortcut"> <img src="images/Editor-name.png" alt="Shortcut"></p> <p>You may create a <strong>New file</strong> or an <strong>Open file</strong> shortcut in the launcher. The <strong>New file</strong> widget will create an shortcut to open a new file in Editor. The <strong>Open file</strong> widget will pop up a dialog showing the file chooser. You may choose a file or use the <strong>Storage</strong> button. You may cancel and fill in the name and path fields, or edit the name or path fields after choosing a file. Use the <strong>Create</strong> button to create the shortcut. <strong>Note</strong> – content URIs returned by the android file picker will not be resolved.</p> Highlight Syntax https://billthefarmer.github.io/editor/using/highlight-syntax/ Wed, 04 Mar 2020 19:41:14 +0000 https://billthefarmer.github.io/editor/using/highlight-syntax/ <p><img src="images/Editor-syntax.png" alt="Syntax"></p> <p>If the current open file is a C, C++, Objective C, Dart, Go, Java, Javascript, Python, Rust, Shell script, Swift, CSS, HTML, <a href="https://orgmode.org" title="https://orgmode.org">Emacs Org</a> or Markdown file, the keywords, classes comments, strings, etc will be highlighted.</p> <h3 id="selection">Selection</h3> <p>The type of highlighting is selected by file extension. Files with <code>.c</code>, <code>.cc</code>, <code>.c++</code>, <code>.cxx</code>, <code>.m</code>, <code>.h</code>, <code>.dart</code>, <code>.go</code>, <code>.js</code>, <code>.java</code>, <code>.py</code>, <code>.rs</code>, <code>.sh</code>, <code>.swift</code> extensions will be highlighted with &lsquo;C&rsquo; style highlighting. Files with <code>.htm</code>, <code>.html</code> extensions will be highlighted as HTML. Files with <code>.cs</code>, <code>.css</code> extensions will be highlighted as CSS. Files with <code>.md</code> extensions will be highlighted as markdown. Files with <code>.org</code> extensions will be highlighted as Emacs Org.</p> Mode Line https://billthefarmer.github.io/editor/using/mode-line/ Wed, 04 Mar 2020 17:41:40 +0000 https://billthefarmer.github.io/editor/using/mode-line/ <p>If a line of text is found within the first or last two or three lines of the file which matches the mode line pattern, the mode of the editor will be changed after the file is loaded. The pattern is one or more text or punctuation characters, white space, the text <code>ed:</code> followed by one or more option patterns separated by white space.</p> <pre><code># ed: [[no]vw] [[no]ww] [[no]sg] [[no]hs] [cs:u] [th:l|d|s|w|b|r] [ts:l|m|s] [tf:m|p|s] </code></pre> <p>The initial text or punctuation characters are intended to be used to hide the mode line from compilers and interpreters by commenting it out.</p> Word Count https://billthefarmer.github.io/editor/using/word-count/ Mon, 29 Mar 2021 18:47:58 +0100 https://billthefarmer.github.io/editor/using/word-count/ <p>The file word count and character count are shown in the toolbar. Due to the algorithm used, the result may differ from that produced by other utilities.</p> Extended Selection https://billthefarmer.github.io/editor/using/extended-selection/ Wed, 04 Mar 2020 17:42:02 +0000 https://billthefarmer.github.io/editor/using/extended-selection/ <p>If the file being edited is not a plain text file, selections created by double tapping or long touching on the text will be extended to enclosing delimiters (brackets, quotes) on the same text line.</p> Text Size https://billthefarmer.github.io/editor/using/text-size/ Fri, 16 Jul 2021 09:14:58 +0100 https://billthefarmer.github.io/editor/using/text-size/ <p>Text size may be changed from the menu or by pinch or expand gestures on the text or by doubletap and swipe. The response to gestures on large files may be slow or delayed.</p> Unsaved File https://billthefarmer.github.io/editor/using/unsaved-file/ Wed, 04 Mar 2020 17:42:32 +0000 https://billthefarmer.github.io/editor/using/unsaved-file/ <p>If you touch the new, back or open button, and the current file has been modified, you will be prompted whether you want to save it, else the editor will just exit or open a file chooser. The current file may be saved on app pause using the menu option. The scroll position and name will be remembered for the last 10 files opened.</p> Changed File https://billthefarmer.github.io/editor/using/changed-file/ Wed, 04 Mar 2020 17:42:49 +0000 https://billthefarmer.github.io/editor/using/changed-file/ <p>If a file has changed in storage while it was open in the editor, if you attempt to save it, or the app is resumed, you will be prompted whether to overwrite or reload the file.</p> Default File https://billthefarmer.github.io/editor/using/default-file/ Wed, 04 Mar 2020 17:43:09 +0000 https://billthefarmer.github.io/editor/using/default-file/ <p>If there is no open file any text entered will by default be saved in <code>Documents/Editor.txt</code>. This file will be loaded on start if it exists. Use the <strong>Save as</strong> menu item to save it elsewhere.</p> Shared File https://billthefarmer.github.io/editor/using/shared-file/ Wed, 04 Mar 2020 17:43:39 +0000 https://billthefarmer.github.io/editor/using/shared-file/ <p>Text files opened or shared by another app may be viewed and edited. Some apps may share files or text using a <code>content</code> URI that is not resolvable to a path to a file in storage. In that case the editor will read the file into a new file. The <strong>Save</strong> item will save the file in the original location if possible.</p> <p><strong>Note</strong> – Apps that share files will usually only give another app read permission. Use the <strong>Save as</strong> menu item to save the file elsewhere.</p> Keyboard Shortcuts https://billthefarmer.github.io/editor/using/keyboard-shortcuts/ Wed, 21 Jul 2021 19:22:29 +0100 https://billthefarmer.github.io/editor/using/keyboard-shortcuts/ <p>When using an external keyboard, some keyboard shortcuts are implemented:</p> <ul> <li>Ctrl+E – Edit mode</li> <li>Ctrl+Shift+E – View mode</li> <li>Ctrl+F – Search</li> <li>Ctrl+Shift+F – Close search</li> <li>Ctrl+Alt+F – Find next</li> <li>Ctrl+G – Go to</li> <li>Ctrl+M – Show menu</li> <li>Ctrl+N – New file</li> <li>Ctrl+O – Open file</li> <li>Ctrl+S – Save file</li> <li>Ctrl+Shift+S – Save as</li> <li>Ctrl++ – Increase text size</li> <li>Ctrl+- – Decrease text size</li> <li>F3 – Find next</li> <li>F10 – Show menu</li> </ul> <p>Many other shortcuts – Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X, Ctrl+Z are already build in to android.</p> ================================================ FILE: fastlane/metadata/android/en/changelogs/1193.txt ================================================ * Add serif and sans typeface * Update mime types ================================================ FILE: fastlane/metadata/android/en/changelogs/162.txt ================================================ * Update file provider URI resolution * Update build scripts ================================================ FILE: fastlane/metadata/android/en/changelogs/163.txt ================================================ * Character set detection and selection * File size check on loading ================================================ FILE: fastlane/metadata/android/en/changelogs/164.txt ================================================ * Update Portuguese translation ================================================ FILE: fastlane/metadata/android/en/changelogs/165.txt ================================================ * Update French translation * Remove menu radio buttons ================================================ FILE: fastlane/metadata/android/en/changelogs/166.txt ================================================ * Add fix for OxygenOS, android 11 ================================================ FILE: fastlane/metadata/android/en/changelogs/167.txt ================================================ * Ellipsize open recent menu ================================================ FILE: fastlane/metadata/android/en/changelogs/168.txt ================================================ * Fix ellipsize open recent menu ================================================ FILE: fastlane/metadata/android/en/changelogs/169.txt ================================================ * Change charset detector to Mozilla UniversalChardet ================================================ FILE: fastlane/metadata/android/en/changelogs/170.txt ================================================ * Update themes ================================================ FILE: fastlane/metadata/android/en/changelogs/171.txt ================================================ * Add new file shortcut ================================================ FILE: fastlane/metadata/android/en/changelogs/172.txt ================================================ * Optional character set detection * Hungarian translation updated ================================================ FILE: fastlane/metadata/android/en/changelogs/173.txt ================================================ * Add Emacs Org syntax highlighting * Update shell script syntax highlighting ================================================ FILE: fastlane/metadata/android/en/changelogs/174.txt ================================================ * Add Japanese translation ================================================ FILE: fastlane/metadata/android/en/changelogs/175.txt ================================================ * Fix Japanese grammar * Fix save check ================================================ FILE: fastlane/metadata/android/en/changelogs/176.txt ================================================ * Add goto dialog ================================================ FILE: fastlane/metadata/android/en/changelogs/177.txt ================================================ * Add print option ================================================ FILE: fastlane/metadata/android/en/changelogs/178.txt ================================================ * Add Ukranian translation ================================================ FILE: fastlane/metadata/android/en/changelogs/179.txt ================================================ * Update save as dialog * Update goto dialog * Update save content URI ================================================ FILE: fastlane/metadata/android/en/changelogs/180.txt ================================================ * Update file picker, intent filter ================================================ FILE: fastlane/metadata/android/en/changelogs/181.txt ================================================ * Update text selection ================================================ FILE: fastlane/metadata/android/en/changelogs/182.txt ================================================ * Add white theme ================================================ FILE: fastlane/metadata/android/en/changelogs/183.txt ================================================ * Update black, retro themes ================================================ FILE: fastlane/metadata/android/en/changelogs/184.txt ================================================ * Update themes, shortcuts ================================================ FILE: fastlane/metadata/android/en/changelogs/185.txt ================================================ * Add open last option ================================================ FILE: fastlane/metadata/android/en/changelogs/186.txt ================================================ * Add system theme * Add open file shortcut ================================================ FILE: fastlane/metadata/android/en/changelogs/187.txt ================================================ * Check recent files exist ================================================ FILE: fastlane/metadata/android/en/changelogs/188.txt ================================================ * Add Belarusian translation ================================================ FILE: fastlane/metadata/android/en/changelogs/189.txt ================================================ * Fix recent file list ================================================ FILE: fastlane/metadata/android/en/changelogs/190.txt ================================================ * Update icons ================================================ FILE: fastlane/metadata/android/en/changelogs/191.txt ================================================ * Fix search issue ================================================ FILE: fastlane/metadata/android/en/changelogs/192.txt ================================================ * Add Basque (eu) translation ================================================ FILE: fastlane/metadata/android/en/changelogs/194.txt ================================================ * Add Arabic translation * Add keyboard shortcut * Add typefaces ================================================ FILE: fastlane/metadata/android/en/changelogs/195.txt ================================================ * Add keyboard shortcuts ================================================ FILE: fastlane/metadata/android/en/changelogs/196.txt ================================================ * Update Slavic translations * Update text resizing * Update new file ================================================ FILE: fastlane/metadata/android/en/changelogs/197.txt ================================================ * Add Dart and Rust highlighting * Update German translation * Update SDK, build tools ================================================ FILE: fastlane/metadata/android/en/full_description.txt ================================================ This is a very simple generic text editor which may be used standalone or to show or edit any sort of text file from another app. If you select a text file in a file manager or similar app you will be offered the option of using this editor along with whatever other apps you have installed that can show or edit a text file. Files will initially be opened read only, long touch on the display or touch the edit item in the toolbar to enable editing. * Regular expression text search * View markdown in browser or html viewer * Optional auto save * Optional word wrap * Optional suggestions * Optional syntax highlighting * Character set detection and selection * Light/Dark/Black/Retro themes * Small/Medium/Large text size * Monospace/Proportional typefaces ================================================ FILE: fastlane/metadata/android/en/short_description.txt ================================================ Simple generic text editor ================================================ FILE: fastlane/metadata/android/en/title.txt ================================================ Editor ================================================ FILE: fastlane/metadata/android/hu/changelogs/162.txt ================================================ * Fájlszolgáltató URI feloldásának frissítése * Összeállítási parancsfájlok frissítése ================================================ FILE: fastlane/metadata/android/hu/changelogs/163.txt ================================================ * Karakterkészlet felismerése és kiválasztása * Fájlméret ellenőrzése betöltéskor ================================================ FILE: fastlane/metadata/android/hu/changelogs/164.txt ================================================ * Portugál fordítás frissítése ================================================ FILE: fastlane/metadata/android/hu/changelogs/165.txt ================================================ * Francia fordítás frissítése * Menü választógombjainak eltávolítása ================================================ FILE: fastlane/metadata/android/hu/changelogs/166.txt ================================================ * Javítás hozzáadása OxygenOS és Android 11 rendszerekhez ================================================ FILE: fastlane/metadata/android/hu/changelogs/167.txt ================================================ * Legutóbbi megnyitása menü hármasponttal ellátása ================================================ FILE: fastlane/metadata/android/hu/changelogs/168.txt ================================================ * Legutóbbi megnyitása menü hármasponttal ellátásának javítása ================================================ FILE: fastlane/metadata/android/hu/changelogs/169.txt ================================================ * Karakterkészlet-felismerő megváltoztatása a Mozilla UniversalChardet megoldására ================================================ FILE: fastlane/metadata/android/hu/changelogs/170.txt ================================================ * Témák frissítése ================================================ FILE: fastlane/metadata/android/hu/changelogs/171.txt ================================================ * Új fájl hozzáadása gyorsbillentyű ================================================ FILE: fastlane/metadata/android/hu/full_description.txt ================================================ Ez egy nagyon egyszerű, általános szövegszerkesztő, amely önállóan is, vagy bármilyen szöveges fájl egy másik alkalmazásból történő megjelenítésére vagy szerkesztésére is használható. Ha egy fájlkezelőben vagy hasonló alkalmazásban kiválaszt egy szöveges fájlt, akkor felajánlja a lehetőséget, hogy ezt a szerkesztőt bármilyen más, szöveges fájl megjelenítésére vagy szerkesztésére alkalmas telepített alkalmazással együtt használja. A fájlok kezdetben csak olvasásra lesznek megnyitva, a szerkesztés engedélyezéséhez érintse meg hosszan a kijelzőt vagy érintse meg az eszköztáron lévő szerkesztés elemet. * Szövegkeresés reguláris kifejezéssel * Markdown megtekintése a böngészőben vagy a HTML-megjelenítőben * Választható automatikus mentés * Választható szövegtördelés * Választható javaslatok * Választható szintaxiskiemelés * Karakterkészlet felismerése és kiválasztása * Világos, sötét, fekete vagy retró témák * Kicsi, közepes vagy nagy szövegméret * Rögzített szélességű vagy arányos betűkészletek ================================================ FILE: fastlane/metadata/android/hu/short_description.txt ================================================ Egyszerű, általános szövegszerkesztő ================================================ FILE: fastlane/metadata/android/hu/title.txt ================================================ Szerkesztő ================================================ FILE: fastlane/metadata/android/ja/changelogs/162.txt ================================================ * ファイルプロバイダの URI 解析を更新 * ビルドスクリプトの更新 ================================================ FILE: fastlane/metadata/android/ja/changelogs/163.txt ================================================ * 文字セットの検出と選択 * 読み込み時のファイルサイズチェック ================================================ FILE: fastlane/metadata/android/ja/changelogs/164.txt ================================================ * ポルトガル語の翻訳を更新 ================================================ FILE: fastlane/metadata/android/ja/changelogs/165.txt ================================================ * ポルトガル語の翻訳を更新 ================================================ FILE: fastlane/metadata/android/ja/changelogs/166.txt ================================================ * OxygenOS、android 11の修正を追加しました。 ================================================ FILE: fastlane/metadata/android/ja/changelogs/167.txt ================================================ * 最近開いたメニューを楕円形にする ================================================ FILE: fastlane/metadata/android/ja/changelogs/168.txt ================================================ * 最近使ったメニューの楕円の大きさを修正 ================================================ FILE: fastlane/metadata/android/ja/changelogs/169.txt ================================================ * 文字コード検出器をMozilla UniversalChardetに変更する。 ================================================ FILE: fastlane/metadata/android/ja/changelogs/170.txt ================================================ * テーマのアップデート ================================================ FILE: fastlane/metadata/android/ja/changelogs/171.txt ================================================ * 新規ファイルショートカットの追加 ================================================ FILE: fastlane/metadata/android/ja/changelogs/172.txt ================================================ * オプションの文字セット検出 * ハンガリー語翻訳を更新 ================================================ FILE: fastlane/metadata/android/ja/changelogs/173.txt ================================================ * Emacs Orgのシンタックスハイライトの追加 * シェルスクリプトのシンタックスハイライトを更新 ================================================ FILE: fastlane/metadata/android/ja/full_description.txt ================================================ これは非常にシンプルな汎用テキストエディタで、スタンドアロンで使用することも、他のアプリからあらゆる種類のテキストファイルを表示または編集することもできます。ファイルマネージャーや同様のアプリでテキストファイルを選択すると、テキストファイルを表示または編集できる他のアプリがインストールされている場合は、このエディターを使用するオプションが提供されます。初期状態では、ファイルは読み取り専用で開かれます。ディスプレイをロングタッチするか、ツールバーの編集項目をタッチすると、編集が可能になります。 * 正規表現によるテキスト検索 * ブラウザやHTMLビューアでのマークダウン表示 * オプションの自動保存 * オプションのワードラップ * オプションのサジェスト * オプションの構文強調表示 * 文字セットの検出と選択 * ライト/ダーク/ブラック/レトロテーマ * 文字サイズ(小・中・大 * 等幅/プロポーショナル書体 ================================================ FILE: fastlane/metadata/android/ja/short_description.txt ================================================ シンプルな汎用テキストエディタ ================================================ FILE: fastlane/metadata/android/ja/title.txt ================================================ エディター ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle.properties ================================================ android.nonTransitiveRClass=false android.nonFinalResIds=false org.gradle.jvmargs=-Xmx1536M ================================================ FILE: gradlew ================================================ #!/bin/sh # # Copyright © 2015-2021 the original authors. # # 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 # # https://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. # ############################################################################## # # Gradle start up script for POSIX generated by Gradle. # # Important for running: # # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is # noncompliant, but you have some other compliant shell such as ksh or # bash, then to run this script, type that shell name before the whole # command line, like: # # ksh Gradle # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», # «${var#prefix}», «${var%suffix}», and «$( cmd )»; # * compound commands having a testable exit status, especially «case»; # * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # # (2) This script targets any POSIX shell, so it avoids extensions provided # by Bash, Ksh, etc; in particular arrays are avoided. # # The "traditional" practice of packing multiple parameters into a # space-separated string is a well documented source of bugs and security # problems, so this is (mostly) avoided, by progressively accumulating # options in "$@", and eventually passing that to Java. # # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; # see the in-line comments for details. # # There are tweaks for specific operating systems such as AIX, CygWin, # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. # ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link app_path=$0 # Need this for daisy-chained symlinks. while APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} case $link in #( /*) app_path=$link ;; #( *) app_path=$APP_HOME$link ;; esac done APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_NAME="Gradle" APP_BASE_NAME=${0##*/} # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum warn () { echo "$*" } >&2 die () { echo echo "$*" echo exit 1 } >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "$( uname )" in #( CYGWIN* ) cygwin=true ;; #( Darwin* ) darwin=true ;; #( MSYS* | MINGW* ) msys=true ;; #( NONSTOP* ) nonstop=true ;; esac 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" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi # Collect all arguments for the java command, stacking in reverse order: # * args from the command line # * the main class name # * -classpath # * -D...appname settings # * --module-path (only if needed) # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh for arg do if case $arg in #( -*) false ;; # don't mess with options #( /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath [ -e "$t" ] ;; #( *) false ;; esac then arg=$( cygpath --path --ignore --mixed "$arg" ) fi # Roll the args list around exactly as many times as the number of # args, so each arg winds up back in the position where it started, but # possibly modified. # # NB: a `for` loop captures its iteration list before it begins, so # changing the positional parameters here affects neither the number of # iterations, nor the values presented in `arg`. shift # remove old arg set -- "$@" "$arg" # push replacement arg done fi # Collect all arguments for the java command; # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # shell script including quotes and variable substitutions, so put them in # double quotes to make sure that they get re-expanded; and # * put everything else in single quotes, so that it's not re-expanded. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ org.gradle.wrapper.GradleWrapperMain \ "$@" # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. # # In Bash we could simply go: # # readarray ARGS < <( xargs -n1 <<<"$var" ) && # set -- "${ARGS[@]}" "$@" # # but POSIX shell has neither arrays nor command substitution, so instead we # post-process each arg (as a line of input to sed) to backslash-escape any # character that might be a shell metacharacter, then use eval to reverse # that process (while maintaining the separation between arguments), and wrap # the whole thing up as a single "set" statement. # # This will of course break if any of these variables contains a newline or # an unmatched quote. # eval "set -- $( printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | xargs -n1 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | tr '\n' ' ' )" '"$@"' exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @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 set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @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="-Xmx64m" "-Xms64m" @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 execute 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 execute 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 :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 %* :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: src/main/AndroidManifest.xml ================================================ ================================================ FILE: src/main/java/android/support/v4/content/FileProvider.java ================================================ /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.v4.content; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ProviderInfo; import android.content.res.XmlResourceParser; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.os.Environment; import android.os.ParcelFileDescriptor; import android.provider.OpenableColumns; // import android.support.annotation.GuardedBy; import android.text.TextUtils; import android.webkit.MimeTypeMap; import org.xmlpull.v1.XmlPullParserException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * FileProvider is a special subclass of {@link ContentProvider} that facilitates secure sharing * of files associated with an app by creating a content:// {@link Uri} for a file * instead of a file:/// {@link Uri}. *

* A content URI allows you to grant read and write access using * temporary access permissions. When you create an {@link Intent} containing * a content URI, in order to send the content URI * to a client app, you can also call {@link Intent#setFlags(int) Intent.setFlags()} to add * permissions. These permissions are available to the client app for as long as the stack for * a receiving {@link android.app.Activity} is active. For an {@link Intent} going to a * {@link android.app.Service}, the permissions are available as long as the * {@link android.app.Service} is running. *

* In comparison, to control access to a file:/// {@link Uri} you have to modify the * file system permissions of the underlying file. The permissions you provide become available to * any app, and remain in effect until you change them. This level of access is * fundamentally insecure. *

* The increased level of file access security offered by a content URI * makes FileProvider a key part of Android's security infrastructure. *

* This overview of FileProvider includes the following topics: *

*
    *
  1. Defining a FileProvider
  2. *
  3. Specifying Available Files
  4. *
  5. Retrieving the Content URI for a File
  6. *
  7. Granting Temporary Permissions to a URI
  8. *
  9. Serving a Content URI to Another App
  10. *
*

Defining a FileProvider

*

* Since the default functionality of FileProvider includes content URI generation for files, you * don't need to define a subclass in code. Instead, you can include a FileProvider in your app * by specifying it entirely in XML. To specify the FileProvider component itself, add a * <provider> * element to your app manifest. Set the android:name attribute to * android.support.v4.content.FileProvider. Set the android:authorities * attribute to a URI authority based on a domain you control; for example, if you control the * domain mydomain.com you should use the authority * com.mydomain.fileprovider. Set the android:exported attribute to * false; the FileProvider does not need to be public. Set the * android:grantUriPermissions attribute to true, to allow you * to grant temporary access to files. For example: *

 *<manifest>
 *    ...
 *    <application>
 *        ...
 *        <provider
 *            android:name="android.support.v4.content.FileProvider"
 *            android:authorities="com.mydomain.fileprovider"
 *            android:exported="false"
 *            android:grantUriPermissions="true">
 *            ...
 *        </provider>
 *        ...
 *    </application>
 *</manifest>
*

* If you want to override any of the default behavior of FileProvider methods, extend * the FileProvider class and use the fully-qualified class name in the android:name * attribute of the <provider> element. *

Specifying Available Files

* A FileProvider can only generate a content URI for files in directories that you specify * beforehand. To specify a directory, specify the its storage area and path in XML, using child * elements of the <paths> element. * For example, the following paths element tells FileProvider that you intend to * request content URIs for the images/ subdirectory of your private file area. *
 *<paths xmlns:android="http://schemas.android.com/apk/res/android">
 *    <files-path name="my_images" path="images/"/>
 *    ...
 *</paths>
 *
*

* The <paths> element must contain one or more of the following child elements: *

*
*
*
 *<files-path name="name" path="path" />
 *
*
*
* Represents files in the files/ subdirectory of your app's internal storage * area. This subdirectory is the same as the value returned by {@link Context#getFilesDir() * Context.getFilesDir()}. *
*
*
 *<cache-path name="name" path="path" />
 *
*
*
* Represents files in the cache subdirectory of your app's internal storage area. The root path * of this subdirectory is the same as the value returned by {@link Context#getCacheDir() * getCacheDir()}. *
*
*
 *<external-path name="name" path="path" />
 *
*
*
* Represents files in the root of the external storage area. The root path of this subdirectory * is the same as the value returned by * {@link Environment#getExternalStorageDirectory() Environment.getExternalStorageDirectory()}. *
*
*
 *<external-files-path name="name" path="path" />
 *
*
*
* Represents files in the root of your app's external storage area. The root path of this * subdirectory is the same as the value returned by * {@code Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)}. *
*
*
 *<external-cache-path name="name" path="path" />
 *
*
*
* Represents files in the root of your app's external cache area. The root path of this * subdirectory is the same as the value returned by * {@link Context#getExternalCacheDir() Context.getExternalCacheDir()}. *
*
*

* These child elements all use the same attributes: *

*
*
* name="name" *
*
* A URI path segment. To enforce security, this value hides the name of the subdirectory * you're sharing. The subdirectory name for this value is contained in the * path attribute. *
*
* path="path" *
*
* The subdirectory you're sharing. While the name attribute is a URI path * segment, the path value is an actual subdirectory name. Notice that the * value refers to a subdirectory, not an individual file or files. You can't * share a single file by its file name, nor can you specify a subset of files using * wildcards. *
*
*

* You must specify a child element of <paths> for each directory that contains * files for which you want content URIs. For example, these XML elements specify two directories: *

 *<paths xmlns:android="http://schemas.android.com/apk/res/android">
 *    <files-path name="my_images" path="images/"/>
 *    <files-path name="my_docs" path="docs/"/>
 *</paths>
 *
*

* Put the <paths> element and its children in an XML file in your project. * For example, you can add them to a new file called res/xml/file_paths.xml. * To link this file to the FileProvider, add a * <meta-data> element * as a child of the <provider> element that defines the FileProvider. Set the * <meta-data> element's "android:name" attribute to * android.support.FILE_PROVIDER_PATHS. Set the element's "android:resource" attribute * to @xml/file_paths (notice that you don't specify the .xml * extension). For example: *

 *<provider
 *    android:name="android.support.v4.content.FileProvider"
 *    android:authorities="com.mydomain.fileprovider"
 *    android:exported="false"
 *    android:grantUriPermissions="true">
 *    <meta-data
 *        android:name="android.support.FILE_PROVIDER_PATHS"
 *        android:resource="@xml/file_paths" />
 *</provider>
 *
*

Generating the Content URI for a File

*

* To share a file with another app using a content URI, your app has to generate the content URI. * To generate the content URI, create a new {@link File} for the file, then pass the {@link File} * to {@link #getUriForFile(Context, String, File) getUriForFile()}. You can send the content URI * returned by {@link #getUriForFile(Context, String, File) getUriForFile()} to another app in an * {@link android.content.Intent}. The client app that receives the content URI can open the file * and access its contents by calling * {@link android.content.ContentResolver#openFileDescriptor(Uri, String) * ContentResolver.openFileDescriptor} to get a {@link ParcelFileDescriptor}. *

* For example, suppose your app is offering files to other apps with a FileProvider that has the * authority com.mydomain.fileprovider. To get a content URI for the file * default_image.jpg in the images/ subdirectory of your internal storage * add the following code: *

 *File imagePath = new File(Context.getFilesDir(), "images");
 *File newFile = new File(imagePath, "default_image.jpg");
 *Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);
 *
* As a result of the previous snippet, * {@link #getUriForFile(Context, String, File) getUriForFile()} returns the content URI * content://com.mydomain.fileprovider/my_images/default_image.jpg. *

Granting Temporary Permissions to a URI

* To grant an access permission to a content URI returned from * {@link #getUriForFile(Context, String, File) getUriForFile()}, do one of the following: *
    *
  • * Call the method * {@link Context#grantUriPermission(String, Uri, int) * Context.grantUriPermission(package, Uri, mode_flags)} for the content:// * {@link Uri}, using the desired mode flags. This grants temporary access permission for the * content URI to the specified package, according to the value of the * the mode_flags parameter, which you can set to * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}, {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} * or both. The permission remains in effect until you revoke it by calling * {@link Context#revokeUriPermission(Uri, int) revokeUriPermission()} or until the device * reboots. *
  • *
  • * Put the content URI in an {@link Intent} by calling {@link Intent#setData(Uri) setData()}. *
  • *
  • * Next, call the method {@link Intent#setFlags(int) Intent.setFlags()} with either * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} or * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} or both. *
  • *
  • * Finally, send the {@link Intent} to * another app. Most often, you do this by calling * {@link android.app.Activity#setResult(int, android.content.Intent) setResult()}. *

    * Permissions granted in an {@link Intent} remain in effect while the stack of the receiving * {@link android.app.Activity} is active. When the stack finishes, the permissions are * automatically removed. Permissions granted to one {@link android.app.Activity} in a client * app are automatically extended to other components of that app. *

    *
  • *
*

Serving a Content URI to Another App

*

* There are a variety of ways to serve the content URI for a file to a client app. One common way * is for the client app to start your app by calling * {@link android.app.Activity#startActivityForResult(Intent, int, Bundle) startActivityResult()}, * which sends an {@link Intent} to your app to start an {@link android.app.Activity} in your app. * In response, your app can immediately return a content URI to the client app or present a user * interface that allows the user to pick a file. In the latter case, once the user picks the file * your app can return its content URI. In both cases, your app returns the content URI in an * {@link Intent} sent via {@link android.app.Activity#setResult(int, Intent) setResult()}. *

*

* You can also put the content URI in a {@link android.content.ClipData} object and then add the * object to an {@link Intent} you send to a client app. To do this, call * {@link Intent#setClipData(ClipData) Intent.setClipData()}. When you use this approach, you can * add multiple {@link android.content.ClipData} objects to the {@link Intent}, each with its own * content URI. When you call {@link Intent#setFlags(int) Intent.setFlags()} on the {@link Intent} * to set temporary access permissions, the same permissions are applied to all of the content * URIs. *

*

* Note: The {@link Intent#setClipData(ClipData) Intent.setClipData()} method is * only available in platform version 16 (Android 4.1) and later. If you want to maintain * compatibility with previous versions, you should send one content URI at a time in the * {@link Intent}. Set the action to {@link Intent#ACTION_SEND} and put the URI in data by calling * {@link Intent#setData setData()}. *

*

More Information

*

* To learn more about FileProvider, see the Android training class * Sharing Files Securely with URIs. *

*/ public class FileProvider extends ContentProvider { private static final String[] COLUMNS = { OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE }; private static final String META_DATA_FILE_PROVIDER_PATHS = "android.support.FILE_PROVIDER_PATHS"; private static final String TAG_ROOT_PATH = "root-path"; private static final String TAG_FILES_PATH = "files-path"; private static final String TAG_CACHE_PATH = "cache-path"; private static final String TAG_EXTERNAL = "external-path"; private static final String TAG_EXTERNAL_FILES = "external-files-path"; private static final String TAG_EXTERNAL_CACHE = "external-cache-path"; private static final String ATTR_NAME = "name"; private static final String ATTR_PATH = "path"; private static final File DEVICE_ROOT = new File("/"); // @GuardedBy("sCache") private static HashMap sCache = new HashMap(); private PathStrategy mStrategy; /** * The default FileProvider implementation does not need to be initialized. If you want to * override this method, you must provide your own subclass of FileProvider. */ @Override public boolean onCreate() { return true; } /** * After the FileProvider is instantiated, this method is called to provide the system with * information about the provider. * * @param context A {@link Context} for the current component. * @param info A {@link ProviderInfo} for the new provider. */ @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); // Sanity check our security if (info.exported) { throw new SecurityException("Provider must not be exported"); } if (!info.grantUriPermissions) { throw new SecurityException("Provider must grant uri permissions"); } mStrategy = getPathStrategy(context, info.authority); } /** * Return a content URI for a given {@link File}. Specific temporary * permissions for the content URI can be set with * {@link Context#grantUriPermission(String, Uri, int)}, or added * to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then * {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a * content {@link Uri} for file paths defined in their <paths> * meta-data element. See the Class Overview for more information. * * @param context A {@link Context} for the current component. * @param authority The authority of a {@link FileProvider} defined in a * {@code } element in your app's manifest. * @param file A {@link File} pointing to the filename for which you want a * content {@link Uri}. * @return A content URI for the file. * @throws IllegalArgumentException When the given {@link File} is outside * the paths supported by the provider. */ public static Uri getUriForFile(Context context, String authority, File file) { final PathStrategy strategy = getPathStrategy(context, authority); return strategy.getUriForFile(file); } /** * Use a content URI returned by * {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file * managed by the FileProvider. * FileProvider reports the column names defined in {@link android.provider.OpenableColumns}: *
    *
  • {@link android.provider.OpenableColumns#DISPLAY_NAME}
  • *
  • {@link android.provider.OpenableColumns#SIZE}
  • *
* For more information, see * {@link ContentProvider#query(Uri, String[], String, String[], String) * ContentProvider.query()}. * * @param uri A content URI returned by {@link #getUriForFile}. * @param projection The list of columns to put into the {@link Cursor}. If null all columns are * included. * @param selection Selection criteria to apply. If null then all data that matches the content * URI is returned. * @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to * the selection parameter. The query method scans selection from left to * right and iterates through selectionArgs, replacing the current "?" character in * selection with the value at the current position in selectionArgs. The * values are bound to selection as {@link java.lang.String} values. * @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort * the resulting {@link Cursor}. * @return A {@link Cursor} containing the results of the query. * */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // ContentProvider has already checked granted permissions final File file = mStrategy.getFileForUri(uri); if (projection == null) { projection = COLUMNS; } String[] cols = new String[projection.length]; Object[] values = new Object[projection.length]; int i = 0; for (String col : projection) { if (OpenableColumns.DISPLAY_NAME.equals(col)) { cols[i] = OpenableColumns.DISPLAY_NAME; values[i++] = file.getName(); } else if (OpenableColumns.SIZE.equals(col)) { cols[i] = OpenableColumns.SIZE; values[i++] = file.length(); } } cols = copyOf(cols, i); values = copyOf(values, i); final MatrixCursor cursor = new MatrixCursor(cols, 1); cursor.addRow(values); return cursor; } /** * Returns the MIME type of a content URI returned by * {@link #getUriForFile(Context, String, File) getUriForFile()}. * * @param uri A content URI returned by * {@link #getUriForFile(Context, String, File) getUriForFile()}. * @return If the associated file has an extension, the MIME type associated with that * extension; otherwise application/octet-stream. */ @Override public String getType(Uri uri) { // ContentProvider has already checked granted permissions final File file = mStrategy.getFileForUri(uri); final int lastDot = file.getName().lastIndexOf('.'); if (lastDot >= 0) { final String extension = file.getName().substring(lastDot + 1); final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if (mime != null) { return mime; } } return "application/octet-stream"; } /** * By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must * subclass FileProvider if you want to provide different functionality. */ @Override public Uri insert(Uri uri, ContentValues values) { throw new UnsupportedOperationException("No external inserts"); } /** * By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must * subclass FileProvider if you want to provide different functionality. */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { throw new UnsupportedOperationException("No external updates"); } /** * Deletes the file associated with the specified content URI, as * returned by {@link #getUriForFile(Context, String, File) getUriForFile()}. Notice that this * method does not throw an {@link java.io.IOException}; you must check its return value. * * @param uri A content URI for a file, as returned by * {@link #getUriForFile(Context, String, File) getUriForFile()}. * @param selection Ignored. Set to {@code null}. * @param selectionArgs Ignored. Set to {@code null}. * @return 1 if the delete succeeds; otherwise, 0. */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { // ContentProvider has already checked granted permissions final File file = mStrategy.getFileForUri(uri); return file.delete() ? 1 : 0; } /** * By default, FileProvider automatically returns the * {@link ParcelFileDescriptor} for a file associated with a content:// * {@link Uri}. To get the {@link ParcelFileDescriptor}, call * {@link android.content.ContentResolver#openFileDescriptor(Uri, String) * ContentResolver.openFileDescriptor}. * * To override this method, you must provide your own subclass of FileProvider. * * @param uri A content URI associated with a file, as returned by * {@link #getUriForFile(Context, String, File) getUriForFile()}. * @param mode Access mode for the file. May be "r" for read-only access, "rw" for read and * write access, or "rwt" for read and write access that truncates any existing file. * @return A new {@link ParcelFileDescriptor} with which you can access the file. */ @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { // ContentProvider has already checked granted permissions final File file = mStrategy.getFileForUri(uri); final int fileMode = modeToMode(mode); return ParcelFileDescriptor.open(file, fileMode); } /** * Return {@link PathStrategy} for given authority, either by parsing or * returning from cache. */ private static PathStrategy getPathStrategy(Context context, String authority) { PathStrategy strat; synchronized (sCache) { strat = sCache.get(authority); if (strat == null) { try { strat = parsePathStrategy(context, authority); } catch (IOException e) { throw new IllegalArgumentException( "Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e); } catch (XmlPullParserException e) { throw new IllegalArgumentException( "Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e); } sCache.put(authority, strat); } } return strat; } /** * Parse and return {@link PathStrategy} for given authority as defined in * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code }. * * @see #getPathStrategy(Context, String) */ private static PathStrategy parsePathStrategy(Context context, String authority) throws IOException, XmlPullParserException { final SimplePathStrategy strat = new SimplePathStrategy(authority); final ProviderInfo info = context.getPackageManager() .resolveContentProvider(authority, PackageManager.GET_META_DATA); final XmlResourceParser in = info.loadXmlMetaData( context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS); if (in == null) { throw new IllegalArgumentException( "Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data"); } int type; while ((type = in.next()) != END_DOCUMENT) { if (type == START_TAG) { final String tag = in.getName(); final String name = in.getAttributeValue(null, ATTR_NAME); String path = in.getAttributeValue(null, ATTR_PATH); File target = null; if (TAG_ROOT_PATH.equals(tag)) { target = DEVICE_ROOT; } else if (TAG_FILES_PATH.equals(tag)) { target = context.getFilesDir(); } else if (TAG_CACHE_PATH.equals(tag)) { target = context.getCacheDir(); } else if (TAG_EXTERNAL.equals(tag)) { target = Environment.getExternalStorageDirectory(); } else if (TAG_EXTERNAL_FILES.equals(tag)) { target = context.getExternalFilesDir(null); } else if (TAG_EXTERNAL_CACHE.equals(tag)) { target = context.getExternalCacheDir(); } if (target != null) { strat.addRoot(name, buildPath(target, path)); } } } return strat; } /** * Strategy for mapping between {@link File} and {@link Uri}. *

* Strategies must be symmetric so that mapping a {@link File} to a * {@link Uri} and then back to a {@link File} points at the original * target. *

* Strategies must remain consistent across app launches, and not rely on * dynamic state. This ensures that any generated {@link Uri} can still be * resolved if your process is killed and later restarted. * * @see SimplePathStrategy */ interface PathStrategy { /** * Return a {@link Uri} that represents the given {@link File}. */ public Uri getUriForFile(File file); /** * Return a {@link File} that represents the given {@link Uri}. */ public File getFileForUri(Uri uri); } /** * Strategy that provides access to files living under a narrow whitelist of * filesystem roots. It will throw {@link SecurityException} if callers try * accessing files outside the configured roots. *

* For example, if configured with * {@code addRoot("myfiles", context.getFilesDir())}, then * {@code context.getFileStreamPath("foo.txt")} would map to * {@code content://myauthority/myfiles/foo.txt}. */ static class SimplePathStrategy implements PathStrategy { private final String mAuthority; private final HashMap mRoots = new HashMap(); public SimplePathStrategy(String authority) { mAuthority = authority; } /** * Add a mapping from a name to a filesystem root. The provider only offers * access to files that live under configured roots. */ public void addRoot(String name, File root) { if (TextUtils.isEmpty(name)) { throw new IllegalArgumentException("Name must not be empty"); } try { // Resolve to canonical path to keep path checking fast root = root.getCanonicalFile(); } catch (IOException e) { throw new IllegalArgumentException( "Failed to resolve canonical path for " + root, e); } mRoots.put(name, root); } @Override public Uri getUriForFile(File file) { String path; try { path = file.getCanonicalPath(); } catch (IOException e) { throw new IllegalArgumentException("Failed to resolve canonical path for " + file); } // Find the most-specific root path Map.Entry mostSpecific = null; for (Map.Entry root : mRoots.entrySet()) { final String rootPath = root.getValue().getPath(); if (path.startsWith(rootPath) && (mostSpecific == null || rootPath.length() > mostSpecific.getValue().getPath().length())) { mostSpecific = root; } } if (mostSpecific == null) { throw new IllegalArgumentException( "Failed to find configured root that contains " + path); } // Start at first char of path under root final String rootPath = mostSpecific.getValue().getPath(); if (rootPath.endsWith("/")) { path = path.substring(rootPath.length()); } else { path = path.substring(rootPath.length() + 1); } // Encode the tag and path separately path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/"); return new Uri.Builder().scheme("content") .authority(mAuthority).encodedPath(path).build(); } @Override public File getFileForUri(Uri uri) { String path = uri.getEncodedPath(); final int splitIndex = path.indexOf('/', 1); final String tag = Uri.decode(path.substring(1, splitIndex)); path = Uri.decode(path.substring(splitIndex + 1)); final File root = mRoots.get(tag); if (root == null) { throw new IllegalArgumentException("Unable to find configured root for " + uri); } File file = new File(root, path); try { file = file.getCanonicalFile(); } catch (IOException e) { throw new IllegalArgumentException("Failed to resolve canonical path for " + file); } if (!file.getPath().startsWith(root.getPath())) { throw new SecurityException("Resolved path jumped beyond configured root"); } return file; } } /** * Copied from ContentResolver.java */ private static int modeToMode(String mode) { int modeBits; if ("r".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_READ_ONLY; } else if ("w".equals(mode) || "wt".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE; } else if ("wa".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_APPEND; } else if ("rw".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_READ_WRITE | ParcelFileDescriptor.MODE_CREATE; } else if ("rwt".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_READ_WRITE | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE; } else { throw new IllegalArgumentException("Invalid mode: " + mode); } return modeBits; } private static File buildPath(File base, String... segments) { File cur = base; for (String segment : segments) { if (segment != null) { cur = new File(cur, segment); } } return cur; } private static String[] copyOf(String[] original, int newLength) { final String[] result = new String[newLength]; System.arraycopy(original, 0, result, 0, newLength); return result; } private static Object[] copyOf(Object[] original, int newLength) { final Object[] result = new Object[newLength]; System.arraycopy(original, 0, result, 0, newLength); return result; } } ================================================ FILE: src/main/java/com/ibm/icu/text/CharsetDetector.java ================================================ // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /** ******************************************************************************* * Copyright (C) 2005-2016, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* */ package com.ibm.icu.text; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * CharsetDetector provides a facility for detecting the * charset or encoding of character data in an unknown format. * The input data can either be from an input stream or an array of bytes. * The result of the detection operation is a list of possibly matching * charsets, or, for simple use, you can just ask for a Java Reader that * will will work over the input data. *

* Character set detection is at best an imprecise operation. The detection * process will attempt to identify the charset that best matches the characteristics * of the byte data, but the process is partly statistical in nature, and * the results can not be guaranteed to always be correct. *

* For best accuracy in charset detection, the input data should be primarily * in a single language, and a minimum of a few hundred bytes worth of plain text * in the language are needed. The detection process will attempt to * ignore html or xml style markup that could otherwise obscure the content. *

* @stable ICU 3.4 */ public class CharsetDetector { // Question: Should we have getters corresponding to the setters for input text // and declared encoding? // A thought: If we were to create our own type of Java Reader, we could defer // figuring out an actual charset for data that starts out with too much English // only ASCII until the user actually read through to something that didn't look // like 7 bit English. If nothing else ever appeared, we would never need to // actually choose the "real" charset. All assuming that the application just // wants the data, and doesn't care about a char set name. /** * Constructor * * @stable ICU 3.4 */ public CharsetDetector() { } /** * Set the declared encoding for charset detection. * The declared encoding of an input text is an encoding obtained * from an http header or xml declaration or similar source that * can be provided as additional information to the charset detector. * A match between a declared encoding and a possible detected encoding * will raise the quality of that detected encoding by a small delta, * and will also appear as a "reason" for the match. *

* A declared encoding that is incompatible with the input data being * analyzed will not be added to the list of possible encodings. * * @param encoding The declared encoding * * @stable ICU 3.4 */ public CharsetDetector setDeclaredEncoding(String encoding) { fDeclaredEncoding = encoding; return this; } /** * Set the input text (byte) data whose charset is to be detected. * * @param in the input text of unknown encoding * * @return This CharsetDetector * * @stable ICU 3.4 */ public CharsetDetector setText(byte [] in) { fRawInput = in; fRawLength = in.length; return this; } private static final int kBufSize = 8000; /** * Set the input text (byte) data whose charset is to be detected. *

* The input stream that supplies the character data must have markSupported() * == true; the charset detection process will read a small amount of data, * then return the stream to its original position via * the InputStream.reset() operation. The exact amount that will * be read depends on the characteristics of the data itself. * * @param in the input text of unknown encoding * * @return This CharsetDetector * * @stable ICU 3.4 */ public CharsetDetector setText(InputStream in) throws IOException { fInputStream = in; fInputStream.mark(kBufSize); fRawInput = new byte[kBufSize]; // Always make a new buffer because the // previous one may have come from the caller, // in which case we can't touch it. fRawLength = 0; int remainingLength = kBufSize; while (remainingLength > 0 ) { // read() may give data in smallish chunks, esp. for remote sources. Hence, this loop. int bytesRead = fInputStream.read(fRawInput, fRawLength, remainingLength); if (bytesRead <= 0) { break; } fRawLength += bytesRead; remainingLength -= bytesRead; } fInputStream.reset(); return this; } /** * Return the charset that best matches the supplied input data. * * Note though, that because the detection * only looks at the start of the input data, * there is a possibility that the returned charset will fail to handle * the full set of input data. *

* Raise an exception if *

    *
  • no charset appears to match the data.
  • *
  • no input text has been provided
  • *
* * @return a CharsetMatch object representing the best matching charset, or * null if there are no matches. * * @stable ICU 3.4 */ public CharsetMatch detect() { // TODO: A better implementation would be to copy the detect loop from // detectAll(), and cut it short as soon as a match with a high confidence // is found. This is something to be done later, after things are otherwise // working. CharsetMatch matches[] = detectAll(); if (matches == null || matches.length == 0) { return null; } return matches[0]; } /** * Return an array of all charsets that appear to be plausible * matches with the input data. The array is ordered with the * best quality match first. *

* Raise an exception if *

    *
  • no charsets appear to match the input data.
  • *
  • no input text has been provided
  • *
* * @return An array of CharsetMatch objects representing possibly matching charsets. * * @stable ICU 3.4 */ public CharsetMatch[] detectAll() { ArrayList matches = new ArrayList(); MungeInput(); // Strip html markup, collect byte stats. // Iterate over all possible charsets, remember all that // give a match quality > 0. for (int i = 0; i < ALL_CS_RECOGNIZERS.size(); i++) { CSRecognizerInfo rcinfo = ALL_CS_RECOGNIZERS.get(i); boolean active = (fEnabledRecognizers != null) ? fEnabledRecognizers[i] : rcinfo.isDefaultEnabled; if (active) { CharsetMatch m = rcinfo.recognizer.match(this); if (m != null) { matches.add(m); } } } Collections.sort(matches); // CharsetMatch compares on confidence Collections.reverse(matches); // Put best match first. CharsetMatch [] resultArray = new CharsetMatch[matches.size()]; resultArray = matches.toArray(resultArray); return resultArray; } /** * Autodetect the charset of an inputStream, and return a Java Reader * to access the converted input data. *

* This is a convenience method that is equivalent to * this.setDeclaredEncoding(declaredEncoding).setText(in).detect().getReader(); *

* For the input stream that supplies the character data, markSupported() * must be true; the charset detection will read a small amount of data, * then return the stream to its original position via * the InputStream.reset() operation. The exact amount that will * be read depends on the characteristics of the data itself. *

* Raise an exception if no charsets appear to match the input data. * * @param in The source of the byte data in the unknown charset. * * @param declaredEncoding A declared encoding for the data, if available, * or null or an empty string if none is available. * * @stable ICU 3.4 */ public Reader getReader(InputStream in, String declaredEncoding) { fDeclaredEncoding = declaredEncoding; try { setText(in); CharsetMatch match = detect(); if (match == null) { return null; } return match.getReader(); } catch (IOException e) { return null; } } /** * Autodetect the charset of an inputStream, and return a String * containing the converted input data. *

* This is a convenience method that is equivalent to * this.setDeclaredEncoding(declaredEncoding).setText(in).detect().getString(); *

* Raise an exception if no charsets appear to match the input data. * * @param in The source of the byte data in the unknown charset. * * @param declaredEncoding A declared encoding for the data, if available, * or null or an empty string if none is available. * * @stable ICU 3.4 */ public String getString(byte[] in, String declaredEncoding) { fDeclaredEncoding = declaredEncoding; try { setText(in); CharsetMatch match = detect(); if (match == null) { return null; } return match.getString(-1); } catch (IOException e) { return null; } } /** * Get the names of all charsets supported by CharsetDetector class. *

* Note: Multiple different charset encodings in a same family may use * a single shared name in this implementation. For example, this method returns * an array including "ISO-8859-1" (ISO Latin 1), but not including "windows-1252" * (Windows Latin 1). However, actual detection result could be "windows-1252" * when the input data matches Latin 1 code points with any points only available * in "windows-1252". * * @return an array of the names of all charsets supported by * CharsetDetector class. * * @stable ICU 3.4 */ public static String[] getAllDetectableCharsets() { String[] allCharsetNames = new String[ALL_CS_RECOGNIZERS.size()]; for (int i = 0; i < allCharsetNames.length; i++) { allCharsetNames[i] = ALL_CS_RECOGNIZERS.get(i).recognizer.getName(); } return allCharsetNames; } /** * Test whether or not input filtering is enabled. * * @return true if input text will be filtered. * * @see #enableInputFilter * * @stable ICU 3.4 */ public boolean inputFilterEnabled() { return fStripTags; } /** * Enable filtering of input text. If filtering is enabled, * text within angle brackets ("<" and ">") will be removed * before detection. * * @param filter true to enable input text filtering. * * @return The previous setting. * * @stable ICU 3.4 */ public boolean enableInputFilter(boolean filter) { boolean previous = fStripTags; fStripTags = filter; return previous; } /* * MungeInput - after getting a set of raw input data to be analyzed, preprocess * it by removing what appears to be html markup. */ private void MungeInput() { int srci = 0; int dsti = 0; byte b; boolean inMarkup = false; int openTags = 0; int badTags = 0; // // html / xml markup stripping. // quick and dirty, not 100% accurate, but hopefully good enough, statistically. // discard everything within < brackets > // Count how many total '<' and illegal (nested) '<' occur, so we can make some // guess as to whether the input was actually marked up at all. if (fStripTags) { for (srci = 0; srci < fRawLength && dsti < fInputBytes.length; srci++) { b = fRawInput[srci]; if (b == (byte)'<') { if (inMarkup) { badTags++; } inMarkup = true; openTags++; } if (! inMarkup) { fInputBytes[dsti++] = b; } if (b == (byte)'>') { inMarkup = false; } } fInputLen = dsti; } // // If it looks like this input wasn't marked up, or if it looks like it's // essentially nothing but markup abandon the markup stripping. // Detection will have to work on the unstripped input. // if (openTags<5 || openTags/5 < badTags || (fInputLen < 100 && fRawLength>600)) { int limit = fRawLength; if (limit > kBufSize) { limit = kBufSize; } for (srci=0; srci ALL_CS_RECOGNIZERS; static { List list = new ArrayList(); list.add(new CSRecognizerInfo(new CharsetRecog_UTF8(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_Unicode.CharsetRecog_UTF_16_BE(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_Unicode.CharsetRecog_UTF_16_LE(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_Unicode.CharsetRecog_UTF_32_BE(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_Unicode.CharsetRecog_UTF_32_LE(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_mbcs.CharsetRecog_sjis(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_2022.CharsetRecog_2022JP(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_2022.CharsetRecog_2022CN(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_2022.CharsetRecog_2022KR(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_mbcs.CharsetRecog_euc.CharsetRecog_gb_18030(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_mbcs.CharsetRecog_euc.CharsetRecog_euc_jp(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_mbcs.CharsetRecog_euc.CharsetRecog_euc_kr(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_mbcs.CharsetRecog_big5(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_8859_1(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_8859_2(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_8859_5_ru(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_8859_6_ar(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_8859_7_el(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_8859_8_I_he(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_8859_8_he(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_windows_1251(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_windows_1256(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_KOI8_R(), true)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_8859_9_tr(), true)); // IBM 420/424 recognizers are disabled by default list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_IBM424_he_rtl(), false)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_IBM424_he_ltr(), false)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_IBM420_ar_rtl(), false)); list.add(new CSRecognizerInfo(new CharsetRecog_sbcs.CharsetRecog_IBM420_ar_ltr(), false)); ALL_CS_RECOGNIZERS = Collections.unmodifiableList(list); } /** * Get the names of charsets that can be recognized by this CharsetDetector instance. * * @return an array of the names of charsets that can be recognized by this CharsetDetector * instance. * * @internal * @deprecated This API is ICU internal only. */ @Deprecated public String[] getDetectableCharsets() { List csnames = new ArrayList(ALL_CS_RECOGNIZERS.size()); for (int i = 0; i < ALL_CS_RECOGNIZERS.size(); i++) { CSRecognizerInfo rcinfo = ALL_CS_RECOGNIZERS.get(i); boolean active = (fEnabledRecognizers == null) ? rcinfo.isDefaultEnabled : fEnabledRecognizers[i]; if (active) { csnames.add(rcinfo.recognizer.getName()); } } return csnames.toArray(new String[csnames.size()]); } /** * Enable or disable individual charset encoding. * A name of charset encoding must be included in the names returned by * {@link #getAllDetectableCharsets()}. * * @param encoding the name of charset encoding. * @param enabled true to enable, or false to disable the * charset encoding. * @return A reference to this CharsetDetector. * @throws IllegalArgumentException when the name of charset encoding is * not supported. * * @internal * @deprecated This API is ICU internal only. */ @Deprecated public CharsetDetector setDetectableCharset(String encoding, boolean enabled) { int modIdx = -1; boolean isDefaultVal = false; for (int i = 0; i < ALL_CS_RECOGNIZERS.size(); i++) { CSRecognizerInfo csrinfo = ALL_CS_RECOGNIZERS.get(i); if (csrinfo.recognizer.getName().equals(encoding)) { modIdx = i; isDefaultVal = (csrinfo.isDefaultEnabled == enabled); break; } } if (modIdx < 0) { // No matching encoding found throw new IllegalArgumentException("Invalid encoding: " + "\"" + encoding + "\""); } if (fEnabledRecognizers == null && !isDefaultVal) { // Create an array storing the non default setting fEnabledRecognizers = new boolean[ALL_CS_RECOGNIZERS.size()]; // Initialize the array with default info for (int i = 0; i < ALL_CS_RECOGNIZERS.size(); i++) { fEnabledRecognizers[i] = ALL_CS_RECOGNIZERS.get(i).isDefaultEnabled; } } if (fEnabledRecognizers != null) { fEnabledRecognizers[modIdx] = enabled; } return this; } } ================================================ FILE: src/main/java/com/ibm/icu/text/CharsetMatch.java ================================================ // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /** ******************************************************************************* * Copyright (C) 2005-2016, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* */ package com.ibm.icu.text; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; /** * This class represents a charset that has been identified by a CharsetDetector * as a possible encoding for a set of input data. From an instance of this * class, you can ask for a confidence level in the charset identification, * or for Java Reader or String to access the original byte data in Unicode form. *

* Instances of this class are created only by CharsetDetectors. *

* Note: this class has a natural ordering that is inconsistent with equals. * The natural ordering is based on the match confidence value. * * @stable ICU 3.4 */ public class CharsetMatch implements Comparable { /** * Create a java.io.Reader for reading the Unicode character data corresponding * to the original byte data supplied to the Charset detect operation. *

* CAUTION: if the source of the byte data was an InputStream, a Reader * can be created for only one matching char set using this method. If more * than one charset needs to be tried, the caller will need to reset * the InputStream and create InputStreamReaders itself, based on the charset name. * * @return the Reader for the Unicode character data. * * @stable ICU 3.4 */ public Reader getReader() { InputStream inputStream = fInputStream; if (inputStream == null) { inputStream = new ByteArrayInputStream(fRawInput, 0, fRawLength); } try { inputStream.reset(); return new InputStreamReader(inputStream, getName()); } catch (IOException e) { return null; } } /** * Create a Java String from Unicode character data corresponding * to the original byte data supplied to the Charset detect operation. * * @return a String created from the converted input data. * * @stable ICU 3.4 */ public String getString() throws java.io.IOException { return getString(-1); } /** * Create a Java String from Unicode character data corresponding * to the original byte data supplied to the Charset detect operation. * The length of the returned string is limited to the specified size; * the string will be trunctated to this length if necessary. A limit value of * zero or less is ignored, and treated as no limit. * * @param maxLength The maximum length of the String to be created when the * source of the data is an input stream, or -1 for * unlimited length. * @return a String created from the converted input data. * * @stable ICU 3.4 */ public String getString(int maxLength) throws java.io.IOException { String result = null; if (fInputStream != null) { StringBuilder sb = new StringBuilder(); char[] buffer = new char[1024]; Reader reader = getReader(); int max = maxLength < 0? Integer.MAX_VALUE : maxLength; int bytesRead = 0; while ((bytesRead = reader.read(buffer, 0, Math.min(max, 1024))) >= 0) { sb.append(buffer, 0, bytesRead); max -= bytesRead; } reader.close(); return sb.toString(); } else { String name = getName(); /* * getName() may return a name with a suffix 'rtl' or 'ltr'. This cannot * be used to open a charset (e.g. IBM424_rtl). The ending '_rtl' or 'ltr' * should be stripped off before creating the string. */ int startSuffix = name.indexOf("_rtl") < 0 ? name.indexOf("_ltr") : name.indexOf("_rtl"); if (startSuffix > 0) { name = name.substring(0, startSuffix); } result = new String(fRawInput, name); } return result; } /** * Get an indication of the confidence in the charset detected. * Confidence values range from 0-100, with larger numbers indicating * a better match of the input data to the characteristics of the * charset. * * @return the confidence in the charset match * * @stable ICU 3.4 */ public int getConfidence() { return fConfidence; } /** * Get the name of the detected charset. * The name will be one that can be used with other APIs on the * platform that accept charset names. It is the "Canonical name" * as defined by the class java.nio.charset.Charset; for * charsets that are registered with the IANA charset registry, * this is the MIME-preferred registerd name. * * @see java.nio.charset.Charset * @see java.io.InputStreamReader * * @return The name of the charset. * * @stable ICU 3.4 */ public String getName() { return fCharsetName; } /** * Get the ISO code for the language of the detected charset. * * @return The ISO code for the language or null if the language cannot be determined. * * @stable ICU 3.4 */ public String getLanguage() { return fLang; } /** * Compare to other CharsetMatch objects. * Comparison is based on the match confidence value, which * allows CharsetDetector.detectAll() to order its results. * * @param other the CharsetMatch object to compare against. * @return a negative integer, zero, or a positive integer as the * confidence level of this CharsetMatch * is less than, equal to, or greater than that of * the argument. * @throws ClassCastException if the argument is not a CharsetMatch. * @stable ICU 4.4 */ @Override public int compareTo (CharsetMatch other) { int compareResult = 0; if (this.fConfidence > other.fConfidence) { compareResult = 1; } else if (this.fConfidence < other.fConfidence) { compareResult = -1; } return compareResult; } /* * Constructor. Implementation internal */ CharsetMatch(CharsetDetector det, CharsetRecognizer rec, int conf) { fConfidence = conf; // The references to the original application input data must be copied out // of the charset recognizer to here, in case the application resets the // recognizer before using this CharsetMatch. if (det.fInputStream == null) { // We only want the existing input byte data if it came straight from the user, // not if is just the head of a stream. fRawInput = det.fRawInput; fRawLength = det.fRawLength; } fInputStream = det.fInputStream; fCharsetName = rec.getName(); fLang = rec.getLanguage(); } /* * Constructor. Implementation internal */ CharsetMatch(CharsetDetector det, CharsetRecognizer rec, int conf, String csName, String lang) { fConfidence = conf; // The references to the original application input data must be copied out // of the charset recognizer to here, in case the application resets the // recognizer before using this CharsetMatch. if (det.fInputStream == null) { // We only want the existing input byte data if it came straight from the user, // not if is just the head of a stream. fRawInput = det.fRawInput; fRawLength = det.fRawLength; } fInputStream = det.fInputStream; fCharsetName = csName; fLang = lang; } // // Private Data // private int fConfidence; private byte[] fRawInput = null; // Original, untouched input bytes. // If user gave us a byte array, this is it. private int fRawLength; // Length of data in fRawInput array. private InputStream fInputStream = null; // User's input stream, or null if the user // gave us a byte array. private String fCharsetName; // The name of the charset this CharsetMatch // represents. Filled in by the recognizer. private String fLang; // The language, if one was determined by // the recognizer during the detect operation. } ================================================ FILE: src/main/java/com/ibm/icu/text/CharsetRecog_2022.java ================================================ // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ******************************************************************************* * Copyright (C) 2005 - 2012, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* */ package com.ibm.icu.text; /** * class CharsetRecog_2022 part of the ICU charset detection implementation. * This is a superclass for the individual detectors for * each of the detectable members of the ISO 2022 family * of encodings. * * The separate classes are nested within this class. */ abstract class CharsetRecog_2022 extends CharsetRecognizer { /** * Matching function shared among the 2022 detectors JP, CN and KR * Counts up the number of legal an unrecognized escape sequences in * the sample of text, and computes a score based on the total number & * the proportion that fit the encoding. * * * @param text the byte buffer containing text to analyse * @param textLen the size of the text in the byte. * @param escapeSequences the byte escape sequences to test for. * @return match quality, in the range of 0-100. */ int match(byte [] text, int textLen, byte [][] escapeSequences) { int i, j; int escN; int hits = 0; int misses = 0; int shifts = 0; int quality; scanInput: for (i=0; i= 3 && (input[0] & 0xFF) == 0xef && (input[1] & 0xFF) == 0xbb && (input[2] & 0xFF) == 0xbf) { hasBOM = true; } // Scan for multi-byte sequences for (i=0; i=det.fRawLength) { break; } b = input[i]; if ((b & 0xc0) != 0x080) { numInvalid++; break; } if (--trailBytes == 0) { numValid++; break; } } } // Cook up some sort of confidence score, based on presence of a BOM // and the existence of valid and/or invalid multi-byte sequences. confidence = 0; if (hasBOM && numInvalid==0) { confidence = 100; } else if (hasBOM && numValid > numInvalid*10) { confidence = 80; } else if (numValid > 3 && numInvalid == 0) { confidence = 100; } else if (numValid > 0 && numInvalid == 0) { confidence = 80; } else if (numValid == 0 && numInvalid == 0) { // Plain ASCII. Confidence must be > 10, it's more likely than UTF-16, which // accepts ASCII with confidence = 10. // TODO: add plain ASCII as an explicitly detected type. confidence = 15; } else if (numValid > numInvalid*10) { // Probably corrupt utf-8 data. Valid sequences aren't likely by chance. confidence = 25; } return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } } ================================================ FILE: src/main/java/com/ibm/icu/text/CharsetRecog_Unicode.java ================================================ // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ******************************************************************************* * Copyright (C) 1996-2013, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* * */ package com.ibm.icu.text; /** * This class matches UTF-16 and UTF-32, both big- and little-endian. The * BOM will be used if it is present. */ abstract class CharsetRecog_Unicode extends CharsetRecognizer { /* (non-Javadoc) * @see com.ibm.icu.text.CharsetRecognizer#getName() */ @Override abstract String getName(); /* (non-Javadoc) * @see com.ibm.icu.text.CharsetRecognizer#match(com.ibm.icu.text.CharsetDetector) */ @Override abstract CharsetMatch match(CharsetDetector det); static int codeUnit16FromBytes(byte hi, byte lo) { return ((hi & 0xff) << 8) | (lo & 0xff); } // UTF-16 confidence calculation. Very simple minded, but better than nothing. // Any 8 bit non-control characters bump the confidence up. These have a zero high byte, // and are very likely to be UTF-16, although they could also be part of a UTF-32 code. // NULs are a contra-indication, they will appear commonly if the actual encoding is UTF-32. // NULs should be rare in actual text. static int adjustConfidence(int codeUnit, int confidence) { if (codeUnit == 0) { confidence -= 10; } else if ((codeUnit >= 0x20 && codeUnit <= 0xff) || codeUnit == 0x0a) { confidence += 10; } if (confidence < 0) { confidence = 0; } else if (confidence > 100) { confidence = 100; } return confidence; } static class CharsetRecog_UTF_16_BE extends CharsetRecog_Unicode { @Override String getName() { return "UTF-16BE"; } @Override CharsetMatch match(CharsetDetector det) { byte[] input = det.fRawInput; int confidence = 10; int bytesToCheck = Math.min(input.length, 30); for (int charIndex=0; charIndex 0) { return new CharsetMatch(det, this, confidence); } return null; } } static class CharsetRecog_UTF_16_LE extends CharsetRecog_Unicode { @Override String getName() { return "UTF-16LE"; } @Override CharsetMatch match(CharsetDetector det) { byte[] input = det.fRawInput; int confidence = 10; int bytesToCheck = Math.min(input.length, 30); for (int charIndex=0; charIndex 0) { return new CharsetMatch(det, this, confidence); } return null; } } static abstract class CharsetRecog_UTF_32 extends CharsetRecog_Unicode { abstract int getChar(byte[] input, int index); @Override abstract String getName(); @Override CharsetMatch match(CharsetDetector det) { byte[] input = det.fRawInput; int limit = (det.fRawLength / 4) * 4; int numValid = 0; int numInvalid = 0; boolean hasBOM = false; int confidence = 0; if (limit==0) { return null; } if (getChar(input, 0) == 0x0000FEFF) { hasBOM = true; } for(int i = 0; i < limit; i += 4) { int ch = getChar(input, i); if (ch < 0 || ch >= 0x10FFFF || (ch >= 0xD800 && ch <= 0xDFFF)) { numInvalid += 1; } else { numValid += 1; } } // Cook up some sort of confidence score, based on presence of a BOM // and the existence of valid and/or invalid multi-byte sequences. if (hasBOM && numInvalid==0) { confidence = 100; } else if (hasBOM && numValid > numInvalid*10) { confidence = 80; } else if (numValid > 3 && numInvalid == 0) { confidence = 100; } else if (numValid > 0 && numInvalid == 0) { confidence = 80; } else if (numValid > numInvalid*10) { // Probably corrupt UTF-32BE data. Valid sequences aren't likely by chance. confidence = 25; } return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } } static class CharsetRecog_UTF_32_BE extends CharsetRecog_UTF_32 { @Override int getChar(byte[] input, int index) { return (input[index + 0] & 0xFF) << 24 | (input[index + 1] & 0xFF) << 16 | (input[index + 2] & 0xFF) << 8 | (input[index + 3] & 0xFF); } @Override String getName() { return "UTF-32BE"; } } static class CharsetRecog_UTF_32_LE extends CharsetRecog_UTF_32 { @Override int getChar(byte[] input, int index) { return (input[index + 3] & 0xFF) << 24 | (input[index + 2] & 0xFF) << 16 | (input[index + 1] & 0xFF) << 8 | (input[index + 0] & 0xFF); } @Override String getName() { return "UTF-32LE"; } } } ================================================ FILE: src/main/java/com/ibm/icu/text/CharsetRecog_mbcs.java ================================================ // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* **************************************************************************** * Copyright (C) 2005-2012, International Business Machines Corporation and * * others. All Rights Reserved. * **************************************************************************** * */ package com.ibm.icu.text; import java.util.Arrays; /** * CharsetRecognizer implementation for Asian - double or multi-byte - charsets. * Match is determined mostly by the input data adhering to the * encoding scheme for the charset, and, optionally, * frequency-of-occurrence of characters. *

* Instances of this class are singletons, one per encoding * being recognized. They are created in the main * CharsetDetector class and kept in the global list of available * encodings to be checked. The specific encoding being recognized * is determined by subclass. */ abstract class CharsetRecog_mbcs extends CharsetRecognizer { /** * Get the IANA name of this charset. * @return the charset name. */ @Override abstract String getName() ; /** * Test the match of this charset with the input text data * which is obtained via the CharsetDetector object. * * @param det The CharsetDetector, which contains the input text * to be checked for being in this charset. * @return Two values packed into one int (Damn java, anyhow) *
* bits 0-7: the match confidence, ranging from 0-100 *
* bits 8-15: The match reason, an enum-like value. */ int match(CharsetDetector det, int [] commonChars) { @SuppressWarnings("unused") int singleByteCharCount = 0; //TODO Do we really need this? int doubleByteCharCount = 0; int commonCharCount = 0; int badCharCount = 0; int totalCharCount = 0; int confidence = 0; iteratedChar iter = new iteratedChar(); detectBlock: { for (iter.reset(); nextChar(iter, det);) { totalCharCount++; if (iter.error) { badCharCount++; } else { long cv = iter.charValue & 0xFFFFFFFFL; if (cv <= 0xff) { singleByteCharCount++; } else { doubleByteCharCount++; if (commonChars != null) { // NOTE: This assumes that there are no 4-byte common chars. if (Arrays.binarySearch(commonChars, (int) cv) >= 0) { commonCharCount++; } } } } if (badCharCount >= 2 && badCharCount*5 >= doubleByteCharCount) { // Bail out early if the byte data is not matching the encoding scheme. break detectBlock; } } if (doubleByteCharCount <= 10 && badCharCount== 0) { // Not many multi-byte chars. if (doubleByteCharCount == 0 && totalCharCount < 10) { // There weren't any multibyte sequences, and there was a low density of non-ASCII single bytes. // We don't have enough data to have any confidence. // Statistical analysis of single byte non-ASCII characters would probably help here. confidence = 0; } else { // ASCII or ISO file? It's probably not our encoding, // but is not incompatible with our encoding, so don't give it a zero. confidence = 10; } break detectBlock; } // // No match if there are too many characters that don't fit the encoding scheme. // (should we have zero tolerance for these?) // if (doubleByteCharCount < 20*badCharCount) { confidence = 0; break detectBlock; } if (commonChars == null) { // We have no statistics on frequently occurring characters. // Assess confidence purely on having a reasonable number of // multi-byte characters (the more the better confidence = 30 + doubleByteCharCount - 20*badCharCount; if (confidence > 100) { confidence = 100; } }else { // // Frequency of occurrence statistics exist. // double maxVal = Math.log((float)doubleByteCharCount / 4); double scaleFactor = 90.0 / maxVal; confidence = (int)(Math.log(commonCharCount+1) * scaleFactor + 10); confidence = Math.min(confidence, 100); } } // end of detectBlock: return confidence; } // "Character" iterated character class. // Recognizers for specific mbcs encodings make their "characters" available // by providing a nextChar() function that fills in an instance of iteratedChar // with the next char from the input. // The returned characters are not converted to Unicode, but remain as the raw // bytes (concatenated into an int) from the codepage data. // // For Asian charsets, use the raw input rather than the input that has been // stripped of markup. Detection only considers multi-byte chars, effectively // stripping markup anyway, and double byte chars do occur in markup too. // static class iteratedChar { int charValue = 0; // 1-4 bytes from the raw input data int nextIndex = 0; boolean error = false; boolean done = false; void reset() { charValue = 0; nextIndex = 0; error = false; done = false; } int nextByte(CharsetDetector det) { if (nextIndex >= det.fRawLength) { done = true; return -1; } int byteValue = det.fRawInput[nextIndex++] & 0x00ff; return byteValue; } } /** * Get the next character (however many bytes it is) from the input data * Subclasses for specific charset encodings must implement this function * to get characters according to the rules of their encoding scheme. * * This function is not a method of class iteratedChar only because * that would require a lot of extra derived classes, which is awkward. * @param it The iteratedChar "struct" into which the returned char is placed. * @param det The charset detector, which is needed to get at the input byte data * being iterated over. * @return True if a character was returned, false at end of input. */ abstract boolean nextChar(iteratedChar it, CharsetDetector det); /** * Shift-JIS charset recognizer. * */ static class CharsetRecog_sjis extends CharsetRecog_mbcs { static int [] commonChars = // TODO: This set of data comes from the character frequency- // of-occurrence analysis tool. The data needs to be moved // into a resource and loaded from there. {0x8140, 0x8141, 0x8142, 0x8145, 0x815b, 0x8169, 0x816a, 0x8175, 0x8176, 0x82a0, 0x82a2, 0x82a4, 0x82a9, 0x82aa, 0x82ab, 0x82ad, 0x82af, 0x82b1, 0x82b3, 0x82b5, 0x82b7, 0x82bd, 0x82be, 0x82c1, 0x82c4, 0x82c5, 0x82c6, 0x82c8, 0x82c9, 0x82cc, 0x82cd, 0x82dc, 0x82e0, 0x82e7, 0x82e8, 0x82e9, 0x82ea, 0x82f0, 0x82f1, 0x8341, 0x8343, 0x834e, 0x834f, 0x8358, 0x835e, 0x8362, 0x8367, 0x8375, 0x8376, 0x8389, 0x838a, 0x838b, 0x838d, 0x8393, 0x8e96, 0x93fa, 0x95aa}; @Override boolean nextChar(iteratedChar it, CharsetDetector det) { it.error = false; int firstByte; firstByte = it.charValue = it.nextByte(det); if (firstByte < 0) { return false; } if (firstByte <= 0x7f || (firstByte>0xa0 && firstByte<=0xdf)) { return true; } int secondByte = it.nextByte(det); if (secondByte < 0) { return false; } it.charValue = (firstByte << 8) | secondByte; if (! ((secondByte>=0x40 && secondByte<=0x7f) || (secondByte>=0x80 && secondByte<=0xff))) { // Illegal second byte value. it.error = true; } return true; } @Override CharsetMatch match(CharsetDetector det) { int confidence = match(det, commonChars); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } @Override String getName() { return "Shift_JIS"; } @Override public String getLanguage() { return "ja"; } } /** * Big5 charset recognizer. * */ static class CharsetRecog_big5 extends CharsetRecog_mbcs { static int [] commonChars = // TODO: This set of data comes from the character frequency- // of-occurrence analysis tool. The data needs to be moved // into a resource and loaded from there. {0xa140, 0xa141, 0xa142, 0xa143, 0xa147, 0xa149, 0xa175, 0xa176, 0xa440, 0xa446, 0xa447, 0xa448, 0xa451, 0xa454, 0xa457, 0xa464, 0xa46a, 0xa46c, 0xa477, 0xa4a3, 0xa4a4, 0xa4a7, 0xa4c1, 0xa4ce, 0xa4d1, 0xa4df, 0xa4e8, 0xa4fd, 0xa540, 0xa548, 0xa558, 0xa569, 0xa5cd, 0xa5e7, 0xa657, 0xa661, 0xa662, 0xa668, 0xa670, 0xa6a8, 0xa6b3, 0xa6b9, 0xa6d3, 0xa6db, 0xa6e6, 0xa6f2, 0xa740, 0xa751, 0xa759, 0xa7da, 0xa8a3, 0xa8a5, 0xa8ad, 0xa8d1, 0xa8d3, 0xa8e4, 0xa8fc, 0xa9c0, 0xa9d2, 0xa9f3, 0xaa6b, 0xaaba, 0xaabe, 0xaacc, 0xaafc, 0xac47, 0xac4f, 0xacb0, 0xacd2, 0xad59, 0xaec9, 0xafe0, 0xb0ea, 0xb16f, 0xb2b3, 0xb2c4, 0xb36f, 0xb44c, 0xb44e, 0xb54c, 0xb5a5, 0xb5bd, 0xb5d0, 0xb5d8, 0xb671, 0xb7ed, 0xb867, 0xb944, 0xbad8, 0xbb44, 0xbba1, 0xbdd1, 0xc2c4, 0xc3b9, 0xc440, 0xc45f}; @Override boolean nextChar(iteratedChar it, CharsetDetector det) { it.error = false; int firstByte; firstByte = it.charValue = it.nextByte(det); if (firstByte < 0) { return false; } if (firstByte <= 0x7f || firstByte==0xff) { // single byte character. return true; } int secondByte = it.nextByte(det); if (secondByte < 0) { return false; } it.charValue = (it.charValue << 8) | secondByte; if (secondByte < 0x40 || secondByte ==0x7f || secondByte == 0xff) { it.error = true; } return true; } @Override CharsetMatch match(CharsetDetector det) { int confidence = match(det, commonChars); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } @Override String getName() { return "Big5"; } @Override public String getLanguage() { return "zh"; } } /** * EUC charset recognizers. One abstract class that provides the common function * for getting the next character according to the EUC encoding scheme, * and nested derived classes for EUC_KR, EUC_JP, EUC_CN. * */ abstract static class CharsetRecog_euc extends CharsetRecog_mbcs { /* * (non-Javadoc) * Get the next character value for EUC based encodings. * Character "value" is simply the raw bytes that make up the character * packed into an int. */ @Override boolean nextChar(iteratedChar it, CharsetDetector det) { it.error = false; int firstByte = 0; int secondByte = 0; int thirdByte = 0; //int fourthByte = 0; buildChar: { firstByte = it.charValue = it.nextByte(det); if (firstByte < 0) { // Ran off the end of the input data it.done = true; break buildChar; } if (firstByte <= 0x8d) { // single byte char break buildChar; } secondByte = it.nextByte(det); it.charValue = (it.charValue << 8) | secondByte; if (firstByte >= 0xA1 && firstByte <= 0xfe) { // Two byte Char if (secondByte < 0xa1) { it.error = true; } break buildChar; } if (firstByte == 0x8e) { // Code Set 2. // In EUC-JP, total char size is 2 bytes, only one byte of actual char value. // In EUC-TW, total char size is 4 bytes, three bytes contribute to char value. // We don't know which we've got. // Treat it like EUC-JP. If the data really was EUC-TW, the following two // bytes will look like a well formed 2 byte char. if (secondByte < 0xa1) { it.error = true; } break buildChar; } if (firstByte == 0x8f) { // Code set 3. // Three byte total char size, two bytes of actual char value. thirdByte = it.nextByte(det); it.charValue = (it.charValue << 8) | thirdByte; if (thirdByte < 0xa1) { it.error = true; } } } return (it.done == false); } /** * The charset recognize for EUC-JP. A singleton instance of this class * is created and kept by the public CharsetDetector class */ static class CharsetRecog_euc_jp extends CharsetRecog_euc { static int [] commonChars = // TODO: This set of data comes from the character frequency- // of-occurrence analysis tool. The data needs to be moved // into a resource and loaded from there. {0xa1a1, 0xa1a2, 0xa1a3, 0xa1a6, 0xa1bc, 0xa1ca, 0xa1cb, 0xa1d6, 0xa1d7, 0xa4a2, 0xa4a4, 0xa4a6, 0xa4a8, 0xa4aa, 0xa4ab, 0xa4ac, 0xa4ad, 0xa4af, 0xa4b1, 0xa4b3, 0xa4b5, 0xa4b7, 0xa4b9, 0xa4bb, 0xa4bd, 0xa4bf, 0xa4c0, 0xa4c1, 0xa4c3, 0xa4c4, 0xa4c6, 0xa4c7, 0xa4c8, 0xa4c9, 0xa4ca, 0xa4cb, 0xa4ce, 0xa4cf, 0xa4d0, 0xa4de, 0xa4df, 0xa4e1, 0xa4e2, 0xa4e4, 0xa4e8, 0xa4e9, 0xa4ea, 0xa4eb, 0xa4ec, 0xa4ef, 0xa4f2, 0xa4f3, 0xa5a2, 0xa5a3, 0xa5a4, 0xa5a6, 0xa5a7, 0xa5aa, 0xa5ad, 0xa5af, 0xa5b0, 0xa5b3, 0xa5b5, 0xa5b7, 0xa5b8, 0xa5b9, 0xa5bf, 0xa5c3, 0xa5c6, 0xa5c7, 0xa5c8, 0xa5c9, 0xa5cb, 0xa5d0, 0xa5d5, 0xa5d6, 0xa5d7, 0xa5de, 0xa5e0, 0xa5e1, 0xa5e5, 0xa5e9, 0xa5ea, 0xa5eb, 0xa5ec, 0xa5ed, 0xa5f3, 0xb8a9, 0xb9d4, 0xbaee, 0xbbc8, 0xbef0, 0xbfb7, 0xc4ea, 0xc6fc, 0xc7bd, 0xcab8, 0xcaf3, 0xcbdc, 0xcdd1}; @Override String getName() { return "EUC-JP"; } @Override CharsetMatch match(CharsetDetector det) { int confidence = match(det, commonChars); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } @Override public String getLanguage() { return "ja"; } } /** * The charset recognize for EUC-KR. A singleton instance of this class * is created and kept by the public CharsetDetector class */ static class CharsetRecog_euc_kr extends CharsetRecog_euc { static int [] commonChars = // TODO: This set of data comes from the character frequency- // of-occurrence analysis tool. The data needs to be moved // into a resource and loaded from there. {0xb0a1, 0xb0b3, 0xb0c5, 0xb0cd, 0xb0d4, 0xb0e6, 0xb0ed, 0xb0f8, 0xb0fa, 0xb0fc, 0xb1b8, 0xb1b9, 0xb1c7, 0xb1d7, 0xb1e2, 0xb3aa, 0xb3bb, 0xb4c2, 0xb4cf, 0xb4d9, 0xb4eb, 0xb5a5, 0xb5b5, 0xb5bf, 0xb5c7, 0xb5e9, 0xb6f3, 0xb7af, 0xb7c2, 0xb7ce, 0xb8a6, 0xb8ae, 0xb8b6, 0xb8b8, 0xb8bb, 0xb8e9, 0xb9ab, 0xb9ae, 0xb9cc, 0xb9ce, 0xb9fd, 0xbab8, 0xbace, 0xbad0, 0xbaf1, 0xbbe7, 0xbbf3, 0xbbfd, 0xbcad, 0xbcba, 0xbcd2, 0xbcf6, 0xbdba, 0xbdc0, 0xbdc3, 0xbdc5, 0xbec6, 0xbec8, 0xbedf, 0xbeee, 0xbef8, 0xbefa, 0xbfa1, 0xbfa9, 0xbfc0, 0xbfe4, 0xbfeb, 0xbfec, 0xbff8, 0xc0a7, 0xc0af, 0xc0b8, 0xc0ba, 0xc0bb, 0xc0bd, 0xc0c7, 0xc0cc, 0xc0ce, 0xc0cf, 0xc0d6, 0xc0da, 0xc0e5, 0xc0fb, 0xc0fc, 0xc1a4, 0xc1a6, 0xc1b6, 0xc1d6, 0xc1df, 0xc1f6, 0xc1f8, 0xc4a1, 0xc5cd, 0xc6ae, 0xc7cf, 0xc7d1, 0xc7d2, 0xc7d8, 0xc7e5, 0xc8ad}; @Override String getName() { return "EUC-KR"; } @Override CharsetMatch match(CharsetDetector det) { int confidence = match(det, commonChars); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } @Override public String getLanguage() { return "ko"; } } } /** * * GB-18030 recognizer. Uses simplified Chinese statistics. * */ static class CharsetRecog_gb_18030 extends CharsetRecog_mbcs { /* * (non-Javadoc) * Get the next character value for EUC based encodings. * Character "value" is simply the raw bytes that make up the character * packed into an int. */ @Override boolean nextChar(iteratedChar it, CharsetDetector det) { it.error = false; int firstByte = 0; int secondByte = 0; int thirdByte = 0; int fourthByte = 0; buildChar: { firstByte = it.charValue = it.nextByte(det); if (firstByte < 0) { // Ran off the end of the input data it.done = true; break buildChar; } if (firstByte <= 0x80) { // single byte char break buildChar; } secondByte = it.nextByte(det); it.charValue = (it.charValue << 8) | secondByte; if (firstByte >= 0x81 && firstByte <= 0xFE) { // Two byte Char if ((secondByte >= 0x40 && secondByte <= 0x7E) || (secondByte >=80 && secondByte <=0xFE)) { break buildChar; } // Four byte char if (secondByte >= 0x30 && secondByte <= 0x39) { thirdByte = it.nextByte(det); if (thirdByte >= 0x81 && thirdByte <= 0xFE) { fourthByte = it.nextByte(det); if (fourthByte >= 0x30 && fourthByte <= 0x39) { it.charValue = (it.charValue << 16) | (thirdByte << 8) | fourthByte; break buildChar; } } } it.error = true; break buildChar; } } return (it.done == false); } static int [] commonChars = // TODO: This set of data comes from the character frequency- // of-occurrence analysis tool. The data needs to be moved // into a resource and loaded from there. {0xa1a1, 0xa1a2, 0xa1a3, 0xa1a4, 0xa1b0, 0xa1b1, 0xa1f1, 0xa1f3, 0xa3a1, 0xa3ac, 0xa3ba, 0xb1a8, 0xb1b8, 0xb1be, 0xb2bb, 0xb3c9, 0xb3f6, 0xb4f3, 0xb5bd, 0xb5c4, 0xb5e3, 0xb6af, 0xb6d4, 0xb6e0, 0xb7a2, 0xb7a8, 0xb7bd, 0xb7d6, 0xb7dd, 0xb8b4, 0xb8df, 0xb8f6, 0xb9ab, 0xb9c9, 0xb9d8, 0xb9fa, 0xb9fd, 0xbacd, 0xbba7, 0xbbd6, 0xbbe1, 0xbbfa, 0xbcbc, 0xbcdb, 0xbcfe, 0xbdcc, 0xbecd, 0xbedd, 0xbfb4, 0xbfc6, 0xbfc9, 0xc0b4, 0xc0ed, 0xc1cb, 0xc2db, 0xc3c7, 0xc4dc, 0xc4ea, 0xc5cc, 0xc6f7, 0xc7f8, 0xc8ab, 0xc8cb, 0xc8d5, 0xc8e7, 0xc9cf, 0xc9fa, 0xcab1, 0xcab5, 0xcac7, 0xcad0, 0xcad6, 0xcaf5, 0xcafd, 0xccec, 0xcdf8, 0xceaa, 0xcec4, 0xced2, 0xcee5, 0xcfb5, 0xcfc2, 0xcfd6, 0xd0c2, 0xd0c5, 0xd0d0, 0xd0d4, 0xd1a7, 0xd2aa, 0xd2b2, 0xd2b5, 0xd2bb, 0xd2d4, 0xd3c3, 0xd3d0, 0xd3fd, 0xd4c2, 0xd4da, 0xd5e2, 0xd6d0}; @Override String getName() { return "GB18030"; } @Override CharsetMatch match(CharsetDetector det) { int confidence = match(det, commonChars); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } @Override public String getLanguage() { return "zh"; } } } ================================================ FILE: src/main/java/com/ibm/icu/text/CharsetRecog_sbcs.java ================================================ // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* **************************************************************************** * Copyright (C) 2005-2013, International Business Machines Corporation and * * others. All Rights Reserved. * ************************************************************************** * * */ package com.ibm.icu.text; /** * This class recognizes single-byte encodings. Because the encoding scheme is so * simple, language statistics are used to do the matching. */ abstract class CharsetRecog_sbcs extends CharsetRecognizer { /* (non-Javadoc) * @see com.ibm.icu.text.CharsetRecognizer#getName() */ @Override abstract String getName(); static class NGramParser { // private static final int N_GRAM_SIZE = 3; private static final int N_GRAM_MASK = 0xFFFFFF; protected int byteIndex = 0; private int ngram = 0; private int[] ngramList; protected byte[] byteMap; private int ngramCount; private int hitCount; protected byte spaceChar; public NGramParser(int[] theNgramList, byte[] theByteMap) { ngramList = theNgramList; byteMap = theByteMap; ngram = 0; ngramCount = hitCount = 0; } /* * Binary search for value in table, which must have exactly 64 entries. */ private static int search(int[] table, int value) { int index = 0; if (table[index + 32] <= value) { index += 32; } if (table[index + 16] <= value) { index += 16; } if (table[index + 8] <= value) { index += 8; } if (table[index + 4] <= value) { index += 4; } if (table[index + 2] <= value) { index += 2; } if (table[index + 1] <= value) { index += 1; } if (table[index] > value) { index -= 1; } if (index < 0 || table[index] != value) { return -1; } return index; } private void lookup(int thisNgram) { ngramCount += 1; if (search(ngramList, thisNgram) >= 0) { hitCount += 1; } } protected void addByte(int b) { ngram = ((ngram << 8) + (b & 0xFF)) & N_GRAM_MASK; lookup(ngram); } private int nextByte(CharsetDetector det) { if (byteIndex >= det.fInputLen) { return -1; } return det.fInputBytes[byteIndex++] & 0xFF; } protected void parseCharacters(CharsetDetector det) { int b; boolean ignoreSpace = false; while ((b = nextByte(det)) >= 0) { byte mb = byteMap[b]; // TODO: 0x20 might not be a space in all character sets... if (mb != 0) { if (!(mb == spaceChar && ignoreSpace)) { addByte(mb); } ignoreSpace = (mb == spaceChar); } } } public int parse(CharsetDetector det) { return parse (det, (byte)0x20); } public int parse(CharsetDetector det, byte spaceCh) { this.spaceChar = spaceCh; parseCharacters(det); // TODO: Is this OK? The buffer could have ended in the middle of a word... addByte(spaceChar); double rawPercent = (double) hitCount / (double) ngramCount; // if (rawPercent <= 2.0) { // return 0; // } // TODO - This is a bit of a hack to take care of a case // were we were getting a confidence of 135... if (rawPercent > 0.33) { return 98; } return (int) (rawPercent * 300.0); } } static class NGramParser_IBM420 extends NGramParser { private byte alef = 0x00; protected static byte[] unshapeMap = { /* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F */ /* 0- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 1- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 2- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 3- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 4- */ (byte) 0x40, (byte) 0x40, (byte) 0x42, (byte) 0x42, (byte) 0x44, (byte) 0x45, (byte) 0x46, (byte) 0x47, (byte) 0x47, (byte) 0x49, (byte) 0x4A, (byte) 0x4B, (byte) 0x4C, (byte) 0x4D, (byte) 0x4E, (byte) 0x4F, /* 5- */ (byte) 0x50, (byte) 0x49, (byte) 0x52, (byte) 0x53, (byte) 0x54, (byte) 0x55, (byte) 0x56, (byte) 0x56, (byte) 0x58, (byte) 0x58, (byte) 0x5A, (byte) 0x5B, (byte) 0x5C, (byte) 0x5D, (byte) 0x5E, (byte) 0x5F, /* 6- */ (byte) 0x60, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x63, (byte) 0x65, (byte) 0x65, (byte) 0x67, (byte) 0x67, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, /* 7- */ (byte) 0x69, (byte) 0x71, (byte) 0x71, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x77, (byte) 0x79, (byte) 0x7A, (byte) 0x7B, (byte) 0x7C, (byte) 0x7D, (byte) 0x7E, (byte) 0x7F, /* 8- */ (byte) 0x80, (byte) 0x81, (byte) 0x82, (byte) 0x83, (byte) 0x84, (byte) 0x85, (byte) 0x86, (byte) 0x87, (byte) 0x88, (byte) 0x89, (byte) 0x80, (byte) 0x8B, (byte) 0x8B, (byte) 0x8D, (byte) 0x8D, (byte) 0x8F, /* 9- */ (byte) 0x90, (byte) 0x91, (byte) 0x92, (byte) 0x93, (byte) 0x94, (byte) 0x95, (byte) 0x96, (byte) 0x97, (byte) 0x98, (byte) 0x99, (byte) 0x9A, (byte) 0x9A, (byte) 0x9A, (byte) 0x9A, (byte) 0x9E, (byte) 0x9E, /* A- */ (byte) 0x9E, (byte) 0xA1, (byte) 0xA2, (byte) 0xA3, (byte) 0xA4, (byte) 0xA5, (byte) 0xA6, (byte) 0xA7, (byte) 0xA8, (byte) 0xA9, (byte) 0x9E, (byte) 0xAB, (byte) 0xAB, (byte) 0xAD, (byte) 0xAD, (byte) 0xAF, /* B- */ (byte) 0xAF, (byte) 0xB1, (byte) 0xB2, (byte) 0xB3, (byte) 0xB4, (byte) 0xB5, (byte) 0xB6, (byte) 0xB7, (byte) 0xB8, (byte) 0xB9, (byte) 0xB1, (byte) 0xBB, (byte) 0xBB, (byte) 0xBD, (byte) 0xBD, (byte) 0xBF, /* C- */ (byte) 0xC0, (byte) 0xC1, (byte) 0xC2, (byte) 0xC3, (byte) 0xC4, (byte) 0xC5, (byte) 0xC6, (byte) 0xC7, (byte) 0xC8, (byte) 0xC9, (byte) 0xCA, (byte) 0xBF, (byte) 0xCC, (byte) 0xBF, (byte) 0xCE, (byte) 0xCF, /* D- */ (byte) 0xD0, (byte) 0xD1, (byte) 0xD2, (byte) 0xD3, (byte) 0xD4, (byte) 0xD5, (byte) 0xD6, (byte) 0xD7, (byte) 0xD8, (byte) 0xD9, (byte) 0xDA, (byte) 0xDA, (byte) 0xDC, (byte) 0xDC, (byte) 0xDC, (byte) 0xDF, /* E- */ (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, /* F- */ (byte) 0xF0, (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB, (byte) 0xFC, (byte) 0xFD, (byte) 0xFE, (byte) 0xFF, }; public NGramParser_IBM420(int[] theNgramList, byte[] theByteMap) { super(theNgramList, theByteMap); } private byte isLamAlef(byte b) { if(b == (byte)0xb2 || b == (byte)0xb3){ return (byte)0x47; }else if(b == (byte)0xb4 || b == (byte)0xb5){ return (byte)0x49; }else if(b == (byte)0xb8 || b == (byte)0xb9){ return (byte)0x56; }else return (byte)0x00; } /* * Arabic shaping needs to be done manually. Cannot call ArabicShaping class * because CharsetDetector is dealing with bytes not Unicode code points. We could * convert the bytes to Unicode code points but that would leave us dependent * on CharsetICU which we try to avoid. IBM420 converter amongst different versions * of JDK can produce different results and therefore is also avoided. */ private int nextByte(CharsetDetector det) { if (byteIndex >= det.fInputLen || det.fInputBytes[byteIndex] == 0) { return -1; } int next; alef = isLamAlef(det.fInputBytes[byteIndex]); if(alef != (byte)0x00) next = 0xB1 & 0xFF; else next = unshapeMap[det.fInputBytes[byteIndex]& 0xFF] & 0xFF; byteIndex++; return next; } @Override protected void parseCharacters(CharsetDetector det) { int b; boolean ignoreSpace = false; while ((b = nextByte(det)) >= 0) { byte mb = byteMap[b]; // TODO: 0x20 might not be a space in all character sets... if (mb != 0) { if (!(mb == spaceChar && ignoreSpace)) { addByte(mb); } ignoreSpace = (mb == spaceChar); } if(alef != (byte)0x00){ mb = byteMap[alef & 0xFF]; // TODO: 0x20 might not be a space in all character sets... if (mb != 0) { if (!(mb == spaceChar && ignoreSpace)) { addByte(mb); } ignoreSpace = (mb == spaceChar); } } } } } int match(CharsetDetector det, int[] ngrams, byte[] byteMap) { return match (det, ngrams, byteMap, (byte)0x20); } int match(CharsetDetector det, int[] ngrams, byte[] byteMap, byte spaceChar) { NGramParser parser = new NGramParser(ngrams, byteMap); return parser.parse(det, spaceChar); } int matchIBM420(CharsetDetector det, int[] ngrams, byte[] byteMap, byte spaceChar){ NGramParser_IBM420 parser = new NGramParser_IBM420(ngrams, byteMap); return parser.parse(det, spaceChar); } static class NGramsPlusLang { int[] fNGrams; String fLang; NGramsPlusLang(String la, int [] ng) { fLang = la; fNGrams = ng; } } static class CharsetRecog_8859_1 extends CharsetRecog_sbcs { protected static byte[] byteMap = { (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xAA, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xB5, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xBA, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0xF0, (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0x20, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB, (byte) 0xFC, (byte) 0xFD, (byte) 0xFE, (byte) 0xDF, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0xF0, (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0x20, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB, (byte) 0xFC, (byte) 0xFD, (byte) 0xFE, (byte) 0xFF, }; private static NGramsPlusLang[] ngrams_8859_1 = new NGramsPlusLang[] { new NGramsPlusLang( "da", new int[] { 0x206166, 0x206174, 0x206465, 0x20656E, 0x206572, 0x20666F, 0x206861, 0x206920, 0x206D65, 0x206F67, 0x2070E5, 0x207369, 0x207374, 0x207469, 0x207669, 0x616620, 0x616E20, 0x616E64, 0x617220, 0x617420, 0x646520, 0x64656E, 0x646572, 0x646574, 0x652073, 0x656420, 0x656465, 0x656E20, 0x656E64, 0x657220, 0x657265, 0x657320, 0x657420, 0x666F72, 0x676520, 0x67656E, 0x676572, 0x696765, 0x696C20, 0x696E67, 0x6B6520, 0x6B6B65, 0x6C6572, 0x6C6967, 0x6C6C65, 0x6D6564, 0x6E6465, 0x6E6520, 0x6E6720, 0x6E6765, 0x6F6720, 0x6F6D20, 0x6F7220, 0x70E520, 0x722064, 0x722065, 0x722073, 0x726520, 0x737465, 0x742073, 0x746520, 0x746572, 0x74696C, 0x766572, }), new NGramsPlusLang( "de", new int[] { 0x20616E, 0x206175, 0x206265, 0x206461, 0x206465, 0x206469, 0x206569, 0x206765, 0x206861, 0x20696E, 0x206D69, 0x207363, 0x207365, 0x20756E, 0x207665, 0x20766F, 0x207765, 0x207A75, 0x626572, 0x636820, 0x636865, 0x636874, 0x646173, 0x64656E, 0x646572, 0x646965, 0x652064, 0x652073, 0x65696E, 0x656974, 0x656E20, 0x657220, 0x657320, 0x67656E, 0x68656E, 0x687420, 0x696368, 0x696520, 0x696E20, 0x696E65, 0x697420, 0x6C6963, 0x6C6C65, 0x6E2061, 0x6E2064, 0x6E2073, 0x6E6420, 0x6E6465, 0x6E6520, 0x6E6720, 0x6E6765, 0x6E7465, 0x722064, 0x726465, 0x726569, 0x736368, 0x737465, 0x742064, 0x746520, 0x74656E, 0x746572, 0x756E64, 0x756E67, 0x766572, }), new NGramsPlusLang( "en", new int[] { 0x206120, 0x20616E, 0x206265, 0x20636F, 0x20666F, 0x206861, 0x206865, 0x20696E, 0x206D61, 0x206F66, 0x207072, 0x207265, 0x207361, 0x207374, 0x207468, 0x20746F, 0x207768, 0x616964, 0x616C20, 0x616E20, 0x616E64, 0x617320, 0x617420, 0x617465, 0x617469, 0x642061, 0x642074, 0x652061, 0x652073, 0x652074, 0x656420, 0x656E74, 0x657220, 0x657320, 0x666F72, 0x686174, 0x686520, 0x686572, 0x696420, 0x696E20, 0x696E67, 0x696F6E, 0x697320, 0x6E2061, 0x6E2074, 0x6E6420, 0x6E6720, 0x6E7420, 0x6F6620, 0x6F6E20, 0x6F7220, 0x726520, 0x727320, 0x732061, 0x732074, 0x736169, 0x737420, 0x742074, 0x746572, 0x746861, 0x746865, 0x74696F, 0x746F20, 0x747320, }), new NGramsPlusLang( "es", new int[] { 0x206120, 0x206361, 0x20636F, 0x206465, 0x20656C, 0x20656E, 0x206573, 0x20696E, 0x206C61, 0x206C6F, 0x207061, 0x20706F, 0x207072, 0x207175, 0x207265, 0x207365, 0x20756E, 0x207920, 0x612063, 0x612064, 0x612065, 0x61206C, 0x612070, 0x616369, 0x61646F, 0x616C20, 0x617220, 0x617320, 0x6369F3, 0x636F6E, 0x646520, 0x64656C, 0x646F20, 0x652064, 0x652065, 0x65206C, 0x656C20, 0x656E20, 0x656E74, 0x657320, 0x657374, 0x69656E, 0x69F36E, 0x6C6120, 0x6C6F73, 0x6E2065, 0x6E7465, 0x6F2064, 0x6F2065, 0x6F6E20, 0x6F7220, 0x6F7320, 0x706172, 0x717565, 0x726120, 0x726573, 0x732064, 0x732065, 0x732070, 0x736520, 0x746520, 0x746F20, 0x756520, 0xF36E20, }), new NGramsPlusLang( "fr", new int[] { 0x206175, 0x20636F, 0x206461, 0x206465, 0x206475, 0x20656E, 0x206574, 0x206C61, 0x206C65, 0x207061, 0x20706F, 0x207072, 0x207175, 0x207365, 0x20736F, 0x20756E, 0x20E020, 0x616E74, 0x617469, 0x636520, 0x636F6E, 0x646520, 0x646573, 0x647520, 0x652061, 0x652063, 0x652064, 0x652065, 0x65206C, 0x652070, 0x652073, 0x656E20, 0x656E74, 0x657220, 0x657320, 0x657420, 0x657572, 0x696F6E, 0x697320, 0x697420, 0x6C6120, 0x6C6520, 0x6C6573, 0x6D656E, 0x6E2064, 0x6E6520, 0x6E7320, 0x6E7420, 0x6F6E20, 0x6F6E74, 0x6F7572, 0x717565, 0x72206C, 0x726520, 0x732061, 0x732064, 0x732065, 0x73206C, 0x732070, 0x742064, 0x746520, 0x74696F, 0x756520, 0x757220, }), new NGramsPlusLang( "it", new int[] { 0x20616C, 0x206368, 0x20636F, 0x206465, 0x206469, 0x206520, 0x20696C, 0x20696E, 0x206C61, 0x207065, 0x207072, 0x20756E, 0x612063, 0x612064, 0x612070, 0x612073, 0x61746F, 0x636865, 0x636F6E, 0x64656C, 0x646920, 0x652061, 0x652063, 0x652064, 0x652069, 0x65206C, 0x652070, 0x652073, 0x656C20, 0x656C6C, 0x656E74, 0x657220, 0x686520, 0x692061, 0x692063, 0x692064, 0x692073, 0x696120, 0x696C20, 0x696E20, 0x696F6E, 0x6C6120, 0x6C6520, 0x6C6920, 0x6C6C61, 0x6E6520, 0x6E6920, 0x6E6F20, 0x6E7465, 0x6F2061, 0x6F2064, 0x6F2069, 0x6F2073, 0x6F6E20, 0x6F6E65, 0x706572, 0x726120, 0x726520, 0x736920, 0x746120, 0x746520, 0x746920, 0x746F20, 0x7A696F, }), new NGramsPlusLang( "nl", new int[] { 0x20616C, 0x206265, 0x206461, 0x206465, 0x206469, 0x206565, 0x20656E, 0x206765, 0x206865, 0x20696E, 0x206D61, 0x206D65, 0x206F70, 0x207465, 0x207661, 0x207665, 0x20766F, 0x207765, 0x207A69, 0x61616E, 0x616172, 0x616E20, 0x616E64, 0x617220, 0x617420, 0x636874, 0x646520, 0x64656E, 0x646572, 0x652062, 0x652076, 0x65656E, 0x656572, 0x656E20, 0x657220, 0x657273, 0x657420, 0x67656E, 0x686574, 0x696520, 0x696E20, 0x696E67, 0x697320, 0x6E2062, 0x6E2064, 0x6E2065, 0x6E2068, 0x6E206F, 0x6E2076, 0x6E6465, 0x6E6720, 0x6F6E64, 0x6F6F72, 0x6F7020, 0x6F7220, 0x736368, 0x737465, 0x742064, 0x746520, 0x74656E, 0x746572, 0x76616E, 0x766572, 0x766F6F, }), new NGramsPlusLang( "no", new int[] { 0x206174, 0x206176, 0x206465, 0x20656E, 0x206572, 0x20666F, 0x206861, 0x206920, 0x206D65, 0x206F67, 0x2070E5, 0x207365, 0x20736B, 0x20736F, 0x207374, 0x207469, 0x207669, 0x20E520, 0x616E64, 0x617220, 0x617420, 0x646520, 0x64656E, 0x646574, 0x652073, 0x656420, 0x656E20, 0x656E65, 0x657220, 0x657265, 0x657420, 0x657474, 0x666F72, 0x67656E, 0x696B6B, 0x696C20, 0x696E67, 0x6B6520, 0x6B6B65, 0x6C6520, 0x6C6C65, 0x6D6564, 0x6D656E, 0x6E2073, 0x6E6520, 0x6E6720, 0x6E6765, 0x6E6E65, 0x6F6720, 0x6F6D20, 0x6F7220, 0x70E520, 0x722073, 0x726520, 0x736F6D, 0x737465, 0x742073, 0x746520, 0x74656E, 0x746572, 0x74696C, 0x747420, 0x747465, 0x766572, }), new NGramsPlusLang( "pt", new int[] { 0x206120, 0x20636F, 0x206461, 0x206465, 0x20646F, 0x206520, 0x206573, 0x206D61, 0x206E6F, 0x206F20, 0x207061, 0x20706F, 0x207072, 0x207175, 0x207265, 0x207365, 0x20756D, 0x612061, 0x612063, 0x612064, 0x612070, 0x616465, 0x61646F, 0x616C20, 0x617220, 0x617261, 0x617320, 0x636F6D, 0x636F6E, 0x646120, 0x646520, 0x646F20, 0x646F73, 0x652061, 0x652064, 0x656D20, 0x656E74, 0x657320, 0x657374, 0x696120, 0x696361, 0x6D656E, 0x6E7465, 0x6E746F, 0x6F2061, 0x6F2063, 0x6F2064, 0x6F2065, 0x6F2070, 0x6F7320, 0x706172, 0x717565, 0x726120, 0x726573, 0x732061, 0x732064, 0x732065, 0x732070, 0x737461, 0x746520, 0x746F20, 0x756520, 0xE36F20, 0xE7E36F, }), new NGramsPlusLang( "sv", new int[] { 0x206174, 0x206176, 0x206465, 0x20656E, 0x2066F6, 0x206861, 0x206920, 0x20696E, 0x206B6F, 0x206D65, 0x206F63, 0x2070E5, 0x20736B, 0x20736F, 0x207374, 0x207469, 0x207661, 0x207669, 0x20E472, 0x616465, 0x616E20, 0x616E64, 0x617220, 0x617474, 0x636820, 0x646520, 0x64656E, 0x646572, 0x646574, 0x656420, 0x656E20, 0x657220, 0x657420, 0x66F672, 0x67656E, 0x696C6C, 0x696E67, 0x6B6120, 0x6C6C20, 0x6D6564, 0x6E2073, 0x6E6120, 0x6E6465, 0x6E6720, 0x6E6765, 0x6E696E, 0x6F6368, 0x6F6D20, 0x6F6E20, 0x70E520, 0x722061, 0x722073, 0x726120, 0x736B61, 0x736F6D, 0x742073, 0x746120, 0x746520, 0x746572, 0x74696C, 0x747420, 0x766172, 0xE47220, 0xF67220, }), }; @Override public CharsetMatch match(CharsetDetector det) { String name = det.fC1Bytes ? "windows-1252" : "ISO-8859-1"; int bestConfidenceSoFar = -1; String lang = null; for (NGramsPlusLang ngl: ngrams_8859_1) { int confidence = match(det, ngl.fNGrams, byteMap); if (confidence > bestConfidenceSoFar) { bestConfidenceSoFar = confidence; lang = ngl.fLang; } } return bestConfidenceSoFar <= 0 ? null : new CharsetMatch(det, this, bestConfidenceSoFar, name, lang); } @Override public String getName() { return "ISO-8859-1"; } } static class CharsetRecog_8859_2 extends CharsetRecog_sbcs { protected static byte[] byteMap = { (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xB1, (byte) 0x20, (byte) 0xB3, (byte) 0x20, (byte) 0xB5, (byte) 0xB6, (byte) 0x20, (byte) 0x20, (byte) 0xB9, (byte) 0xBA, (byte) 0xBB, (byte) 0xBC, (byte) 0x20, (byte) 0xBE, (byte) 0xBF, (byte) 0x20, (byte) 0xB1, (byte) 0x20, (byte) 0xB3, (byte) 0x20, (byte) 0xB5, (byte) 0xB6, (byte) 0xB7, (byte) 0x20, (byte) 0xB9, (byte) 0xBA, (byte) 0xBB, (byte) 0xBC, (byte) 0x20, (byte) 0xBE, (byte) 0xBF, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0xF0, (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0x20, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB, (byte) 0xFC, (byte) 0xFD, (byte) 0xFE, (byte) 0xDF, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0xF0, (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0x20, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB, (byte) 0xFC, (byte) 0xFD, (byte) 0xFE, (byte) 0x20, }; private static NGramsPlusLang[] ngrams_8859_2 = new NGramsPlusLang[] { new NGramsPlusLang( "cs", new int[] { 0x206120, 0x206279, 0x20646F, 0x206A65, 0x206E61, 0x206E65, 0x206F20, 0x206F64, 0x20706F, 0x207072, 0x2070F8, 0x20726F, 0x207365, 0x20736F, 0x207374, 0x20746F, 0x207620, 0x207679, 0x207A61, 0x612070, 0x636520, 0x636820, 0x652070, 0x652073, 0x652076, 0x656D20, 0x656EED, 0x686F20, 0x686F64, 0x697374, 0x6A6520, 0x6B7465, 0x6C6520, 0x6C6920, 0x6E6120, 0x6EE920, 0x6EEC20, 0x6EED20, 0x6F2070, 0x6F646E, 0x6F6A69, 0x6F7374, 0x6F7520, 0x6F7661, 0x706F64, 0x706F6A, 0x70726F, 0x70F865, 0x736520, 0x736F75, 0x737461, 0x737469, 0x73746E, 0x746572, 0x746EED, 0x746F20, 0x752070, 0xBE6520, 0xE16EED, 0xE9686F, 0xED2070, 0xED2073, 0xED6D20, 0xF86564, }), new NGramsPlusLang( "hu", new int[] { 0x206120, 0x20617A, 0x206265, 0x206567, 0x20656C, 0x206665, 0x206861, 0x20686F, 0x206973, 0x206B65, 0x206B69, 0x206BF6, 0x206C65, 0x206D61, 0x206D65, 0x206D69, 0x206E65, 0x20737A, 0x207465, 0x20E973, 0x612061, 0x61206B, 0x61206D, 0x612073, 0x616B20, 0x616E20, 0x617A20, 0x62616E, 0x62656E, 0x656779, 0x656B20, 0x656C20, 0x656C65, 0x656D20, 0x656E20, 0x657265, 0x657420, 0x657465, 0x657474, 0x677920, 0x686F67, 0x696E74, 0x697320, 0x6B2061, 0x6BF67A, 0x6D6567, 0x6D696E, 0x6E2061, 0x6E616B, 0x6E656B, 0x6E656D, 0x6E7420, 0x6F6779, 0x732061, 0x737A65, 0x737A74, 0x737AE1, 0x73E967, 0x742061, 0x747420, 0x74E173, 0x7A6572, 0xE16E20, 0xE97320, }), new NGramsPlusLang( "pl", new int[] { 0x20637A, 0x20646F, 0x206920, 0x206A65, 0x206B6F, 0x206D61, 0x206D69, 0x206E61, 0x206E69, 0x206F64, 0x20706F, 0x207072, 0x207369, 0x207720, 0x207769, 0x207779, 0x207A20, 0x207A61, 0x612070, 0x612077, 0x616E69, 0x636820, 0x637A65, 0x637A79, 0x646F20, 0x647A69, 0x652070, 0x652073, 0x652077, 0x65207A, 0x65676F, 0x656A20, 0x656D20, 0x656E69, 0x676F20, 0x696120, 0x696520, 0x69656A, 0x6B6120, 0x6B6920, 0x6B6965, 0x6D6965, 0x6E6120, 0x6E6961, 0x6E6965, 0x6F2070, 0x6F7761, 0x6F7769, 0x706F6C, 0x707261, 0x70726F, 0x70727A, 0x727A65, 0x727A79, 0x7369EA, 0x736B69, 0x737461, 0x776965, 0x796368, 0x796D20, 0x7A6520, 0x7A6965, 0x7A7920, 0xF37720, }), new NGramsPlusLang( "ro", new int[] { 0x206120, 0x206163, 0x206361, 0x206365, 0x20636F, 0x206375, 0x206465, 0x206469, 0x206C61, 0x206D61, 0x207065, 0x207072, 0x207365, 0x2073E3, 0x20756E, 0x20BA69, 0x20EE6E, 0x612063, 0x612064, 0x617265, 0x617420, 0x617465, 0x617520, 0x636172, 0x636F6E, 0x637520, 0x63E320, 0x646520, 0x652061, 0x652063, 0x652064, 0x652070, 0x652073, 0x656120, 0x656920, 0x656C65, 0x656E74, 0x657374, 0x692061, 0x692063, 0x692064, 0x692070, 0x696520, 0x696920, 0x696E20, 0x6C6120, 0x6C6520, 0x6C6F72, 0x6C7569, 0x6E6520, 0x6E7472, 0x6F7220, 0x70656E, 0x726520, 0x726561, 0x727520, 0x73E320, 0x746520, 0x747275, 0x74E320, 0x756920, 0x756C20, 0xBA6920, 0xEE6E20, }) }; @Override public CharsetMatch match(CharsetDetector det) { String name = det.fC1Bytes ? "windows-1250" : "ISO-8859-2"; int bestConfidenceSoFar = -1; String lang = null; for (NGramsPlusLang ngl: ngrams_8859_2) { int confidence = match(det, ngl.fNGrams, byteMap); if (confidence > bestConfidenceSoFar) { bestConfidenceSoFar = confidence; lang = ngl.fLang; } } return bestConfidenceSoFar <= 0 ? null : new CharsetMatch(det, this, bestConfidenceSoFar, name, lang); } @Override public String getName() { return "ISO-8859-2"; } } abstract static class CharsetRecog_8859_5 extends CharsetRecog_sbcs { protected static byte[] byteMap = { (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB, (byte) 0xFC, (byte) 0x20, (byte) 0xFE, (byte) 0xFF, (byte) 0xD0, (byte) 0xD1, (byte) 0xD2, (byte) 0xD3, (byte) 0xD4, (byte) 0xD5, (byte) 0xD6, (byte) 0xD7, (byte) 0xD8, (byte) 0xD9, (byte) 0xDA, (byte) 0xDB, (byte) 0xDC, (byte) 0xDD, (byte) 0xDE, (byte) 0xDF, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0xD0, (byte) 0xD1, (byte) 0xD2, (byte) 0xD3, (byte) 0xD4, (byte) 0xD5, (byte) 0xD6, (byte) 0xD7, (byte) 0xD8, (byte) 0xD9, (byte) 0xDA, (byte) 0xDB, (byte) 0xDC, (byte) 0xDD, (byte) 0xDE, (byte) 0xDF, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0x20, (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB, (byte) 0xFC, (byte) 0x20, (byte) 0xFE, (byte) 0xFF, }; @Override public String getName() { return "ISO-8859-5"; } } static class CharsetRecog_8859_5_ru extends CharsetRecog_8859_5 { private static int[] ngrams = { 0x20D220, 0x20D2DE, 0x20D4DE, 0x20D7D0, 0x20D820, 0x20DAD0, 0x20DADE, 0x20DDD0, 0x20DDD5, 0x20DED1, 0x20DFDE, 0x20DFE0, 0x20E0D0, 0x20E1DE, 0x20E1E2, 0x20E2DE, 0x20E7E2, 0x20EDE2, 0xD0DDD8, 0xD0E2EC, 0xD3DE20, 0xD5DBEC, 0xD5DDD8, 0xD5E1E2, 0xD5E220, 0xD820DF, 0xD8D520, 0xD8D820, 0xD8EF20, 0xDBD5DD, 0xDBD820, 0xDBECDD, 0xDDD020, 0xDDD520, 0xDDD8D5, 0xDDD8EF, 0xDDDE20, 0xDDDED2, 0xDE20D2, 0xDE20DF, 0xDE20E1, 0xDED220, 0xDED2D0, 0xDED3DE, 0xDED920, 0xDEDBEC, 0xDEDC20, 0xDEE1E2, 0xDFDEDB, 0xDFE0D5, 0xDFE0D8, 0xDFE0DE, 0xE0D0D2, 0xE0D5D4, 0xE1E2D0, 0xE1E2D2, 0xE1E2D8, 0xE1EF20, 0xE2D5DB, 0xE2DE20, 0xE2DEE0, 0xE2EC20, 0xE7E2DE, 0xEBE520, }; @Override public String getLanguage() { return "ru"; } @Override public CharsetMatch match(CharsetDetector det) { int confidence = match(det, ngrams, byteMap); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } } abstract static class CharsetRecog_8859_6 extends CharsetRecog_sbcs { protected static byte[] byteMap = { (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xC1, (byte) 0xC2, (byte) 0xC3, (byte) 0xC4, (byte) 0xC5, (byte) 0xC6, (byte) 0xC7, (byte) 0xC8, (byte) 0xC9, (byte) 0xCA, (byte) 0xCB, (byte) 0xCC, (byte) 0xCD, (byte) 0xCE, (byte) 0xCF, (byte) 0xD0, (byte) 0xD1, (byte) 0xD2, (byte) 0xD3, (byte) 0xD4, (byte) 0xD5, (byte) 0xD6, (byte) 0xD7, (byte) 0xD8, (byte) 0xD9, (byte) 0xDA, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, }; @Override public String getName() { return "ISO-8859-6"; } } static class CharsetRecog_8859_6_ar extends CharsetRecog_8859_6 { private static int[] ngrams = { 0x20C7E4, 0x20C7E6, 0x20C8C7, 0x20D9E4, 0x20E1EA, 0x20E4E4, 0x20E5E6, 0x20E8C7, 0xC720C7, 0xC7C120, 0xC7CA20, 0xC7D120, 0xC7E420, 0xC7E4C3, 0xC7E4C7, 0xC7E4C8, 0xC7E4CA, 0xC7E4CC, 0xC7E4CD, 0xC7E4CF, 0xC7E4D3, 0xC7E4D9, 0xC7E4E2, 0xC7E4E5, 0xC7E4E8, 0xC7E4EA, 0xC7E520, 0xC7E620, 0xC7E6CA, 0xC820C7, 0xC920C7, 0xC920E1, 0xC920E4, 0xC920E5, 0xC920E8, 0xCA20C7, 0xCF20C7, 0xCFC920, 0xD120C7, 0xD1C920, 0xD320C7, 0xD920C7, 0xD9E4E9, 0xE1EA20, 0xE420C7, 0xE4C920, 0xE4E920, 0xE4EA20, 0xE520C7, 0xE5C720, 0xE5C920, 0xE5E620, 0xE620C7, 0xE720C7, 0xE7C720, 0xE8C7E4, 0xE8E620, 0xE920C7, 0xEA20C7, 0xEA20E5, 0xEA20E8, 0xEAC920, 0xEAD120, 0xEAE620, }; @Override public String getLanguage() { return "ar"; } @Override public CharsetMatch match(CharsetDetector det) { int confidence = match(det, ngrams, byteMap); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } } abstract static class CharsetRecog_8859_7 extends CharsetRecog_sbcs { protected static byte[] byteMap = { (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xA1, (byte) 0xA2, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xDC, (byte) 0x20, (byte) 0xDD, (byte) 0xDE, (byte) 0xDF, (byte) 0x20, (byte) 0xFC, (byte) 0x20, (byte) 0xFD, (byte) 0xFE, (byte) 0xC0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0xF0, (byte) 0xF1, (byte) 0x20, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB, (byte) 0xDC, (byte) 0xDD, (byte) 0xDE, (byte) 0xDF, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0xF0, (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB, (byte) 0xFC, (byte) 0xFD, (byte) 0xFE, (byte) 0x20, }; @Override public String getName() { return "ISO-8859-7"; } } static class CharsetRecog_8859_7_el extends CharsetRecog_8859_7 { private static int[] ngrams = { 0x20E1ED, 0x20E1F0, 0x20E3E9, 0x20E4E9, 0x20E5F0, 0x20E720, 0x20EAE1, 0x20ECE5, 0x20EDE1, 0x20EF20, 0x20F0E1, 0x20F0EF, 0x20F0F1, 0x20F3F4, 0x20F3F5, 0x20F4E7, 0x20F4EF, 0xDFE120, 0xE120E1, 0xE120F4, 0xE1E920, 0xE1ED20, 0xE1F0FC, 0xE1F220, 0xE3E9E1, 0xE5E920, 0xE5F220, 0xE720F4, 0xE7ED20, 0xE7F220, 0xE920F4, 0xE9E120, 0xE9EADE, 0xE9F220, 0xEAE1E9, 0xEAE1F4, 0xECE520, 0xED20E1, 0xED20E5, 0xED20F0, 0xEDE120, 0xEFF220, 0xEFF520, 0xF0EFF5, 0xF0F1EF, 0xF0FC20, 0xF220E1, 0xF220E5, 0xF220EA, 0xF220F0, 0xF220F4, 0xF3E520, 0xF3E720, 0xF3F4EF, 0xF4E120, 0xF4E1E9, 0xF4E7ED, 0xF4E7F2, 0xF4E9EA, 0xF4EF20, 0xF4EFF5, 0xF4F9ED, 0xF9ED20, 0xFEED20, }; @Override public String getLanguage() { return "el"; } @Override public CharsetMatch match(CharsetDetector det) { String name = det.fC1Bytes ? "windows-1253" : "ISO-8859-7"; int confidence = match(det, ngrams, byteMap); return confidence == 0 ? null : new CharsetMatch(det, this, confidence, name, "el"); } } abstract static class CharsetRecog_8859_8 extends CharsetRecog_sbcs { protected static byte[] byteMap = { (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xB5, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0xF0, (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, }; @Override public String getName() { return "ISO-8859-8"; } } static class CharsetRecog_8859_8_I_he extends CharsetRecog_8859_8 { private static int[] ngrams = { 0x20E0E5, 0x20E0E7, 0x20E0E9, 0x20E0FA, 0x20E1E9, 0x20E1EE, 0x20E4E0, 0x20E4E5, 0x20E4E9, 0x20E4EE, 0x20E4F2, 0x20E4F9, 0x20E4FA, 0x20ECE0, 0x20ECE4, 0x20EEE0, 0x20F2EC, 0x20F9EC, 0xE0FA20, 0xE420E0, 0xE420E1, 0xE420E4, 0xE420EC, 0xE420EE, 0xE420F9, 0xE4E5E0, 0xE5E020, 0xE5ED20, 0xE5EF20, 0xE5F820, 0xE5FA20, 0xE920E4, 0xE9E420, 0xE9E5FA, 0xE9E9ED, 0xE9ED20, 0xE9EF20, 0xE9F820, 0xE9FA20, 0xEC20E0, 0xEC20E4, 0xECE020, 0xECE420, 0xED20E0, 0xED20E1, 0xED20E4, 0xED20EC, 0xED20EE, 0xED20F9, 0xEEE420, 0xEF20E4, 0xF0E420, 0xF0E920, 0xF0E9ED, 0xF2EC20, 0xF820E4, 0xF8E9ED, 0xF9EC20, 0xFA20E0, 0xFA20E1, 0xFA20E4, 0xFA20EC, 0xFA20EE, 0xFA20F9, }; @Override public String getName() { return "ISO-8859-8-I"; } @Override public String getLanguage() { return "he"; } @Override public CharsetMatch match(CharsetDetector det) { String name = det.fC1Bytes ? "windows-1255" : "ISO-8859-8-I"; int confidence = match(det, ngrams, byteMap); return confidence == 0 ? null : new CharsetMatch(det, this, confidence, name, "he"); } } static class CharsetRecog_8859_8_he extends CharsetRecog_8859_8 { private static int[] ngrams = { 0x20E0E5, 0x20E0EC, 0x20E4E9, 0x20E4EC, 0x20E4EE, 0x20E4F0, 0x20E9F0, 0x20ECF2, 0x20ECF9, 0x20EDE5, 0x20EDE9, 0x20EFE5, 0x20EFE9, 0x20F8E5, 0x20F8E9, 0x20FAE0, 0x20FAE5, 0x20FAE9, 0xE020E4, 0xE020EC, 0xE020ED, 0xE020FA, 0xE0E420, 0xE0E5E4, 0xE0EC20, 0xE0EE20, 0xE120E4, 0xE120ED, 0xE120FA, 0xE420E4, 0xE420E9, 0xE420EC, 0xE420ED, 0xE420EF, 0xE420F8, 0xE420FA, 0xE4EC20, 0xE5E020, 0xE5E420, 0xE7E020, 0xE9E020, 0xE9E120, 0xE9E420, 0xEC20E4, 0xEC20ED, 0xEC20FA, 0xECF220, 0xECF920, 0xEDE9E9, 0xEDE9F0, 0xEDE9F8, 0xEE20E4, 0xEE20ED, 0xEE20FA, 0xEEE120, 0xEEE420, 0xF2E420, 0xF920E4, 0xF920ED, 0xF920FA, 0xF9E420, 0xFAE020, 0xFAE420, 0xFAE5E9, }; @Override public String getLanguage() { return "he"; } @Override public CharsetMatch match(CharsetDetector det) { String name = det.fC1Bytes ? "windows-1255" : "ISO-8859-8"; int confidence = match(det, ngrams, byteMap); return confidence == 0 ? null : new CharsetMatch(det, this, confidence, name, "he"); } } abstract static class CharsetRecog_8859_9 extends CharsetRecog_sbcs { protected static byte[] byteMap = { (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xAA, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xB5, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xBA, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0xF0, (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0x20, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB, (byte) 0xFC, (byte) 0x69, (byte) 0xFE, (byte) 0xDF, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0xF0, (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0x20, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB, (byte) 0xFC, (byte) 0xFD, (byte) 0xFE, (byte) 0xFF, }; @Override public String getName() { return "ISO-8859-9"; } } static class CharsetRecog_8859_9_tr extends CharsetRecog_8859_9 { private static int[] ngrams = { 0x206261, 0x206269, 0x206275, 0x206461, 0x206465, 0x206765, 0x206861, 0x20696C, 0x206B61, 0x206B6F, 0x206D61, 0x206F6C, 0x207361, 0x207461, 0x207665, 0x207961, 0x612062, 0x616B20, 0x616C61, 0x616D61, 0x616E20, 0x616EFD, 0x617220, 0x617261, 0x6172FD, 0x6173FD, 0x617961, 0x626972, 0x646120, 0x646520, 0x646920, 0x652062, 0x65206B, 0x656469, 0x656E20, 0x657220, 0x657269, 0x657369, 0x696C65, 0x696E20, 0x696E69, 0x697220, 0x6C616E, 0x6C6172, 0x6C6520, 0x6C6572, 0x6E2061, 0x6E2062, 0x6E206B, 0x6E6461, 0x6E6465, 0x6E6520, 0x6E6920, 0x6E696E, 0x6EFD20, 0x72696E, 0x72FD6E, 0x766520, 0x796120, 0x796F72, 0xFD6E20, 0xFD6E64, 0xFD6EFD, 0xFDF0FD, }; @Override public String getLanguage() { return "tr"; } @Override public CharsetMatch match(CharsetDetector det) { String name = det.fC1Bytes ? "windows-1254" : "ISO-8859-9"; int confidence = match(det, ngrams, byteMap); return confidence == 0 ? null : new CharsetMatch(det, this, confidence, name, "tr"); } } static class CharsetRecog_windows_1251 extends CharsetRecog_sbcs { private static int[] ngrams = { 0x20E220, 0x20E2EE, 0x20E4EE, 0x20E7E0, 0x20E820, 0x20EAE0, 0x20EAEE, 0x20EDE0, 0x20EDE5, 0x20EEE1, 0x20EFEE, 0x20EFF0, 0x20F0E0, 0x20F1EE, 0x20F1F2, 0x20F2EE, 0x20F7F2, 0x20FDF2, 0xE0EDE8, 0xE0F2FC, 0xE3EE20, 0xE5EBFC, 0xE5EDE8, 0xE5F1F2, 0xE5F220, 0xE820EF, 0xE8E520, 0xE8E820, 0xE8FF20, 0xEBE5ED, 0xEBE820, 0xEBFCED, 0xEDE020, 0xEDE520, 0xEDE8E5, 0xEDE8FF, 0xEDEE20, 0xEDEEE2, 0xEE20E2, 0xEE20EF, 0xEE20F1, 0xEEE220, 0xEEE2E0, 0xEEE3EE, 0xEEE920, 0xEEEBFC, 0xEEEC20, 0xEEF1F2, 0xEFEEEB, 0xEFF0E5, 0xEFF0E8, 0xEFF0EE, 0xF0E0E2, 0xF0E5E4, 0xF1F2E0, 0xF1F2E2, 0xF1F2E8, 0xF1FF20, 0xF2E5EB, 0xF2EE20, 0xF2EEF0, 0xF2FC20, 0xF7F2EE, 0xFBF520, }; private static byte[] byteMap = { (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x90, (byte) 0x83, (byte) 0x20, (byte) 0x83, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x9A, (byte) 0x20, (byte) 0x9C, (byte) 0x9D, (byte) 0x9E, (byte) 0x9F, (byte) 0x90, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x9A, (byte) 0x20, (byte) 0x9C, (byte) 0x9D, (byte) 0x9E, (byte) 0x9F, (byte) 0x20, (byte) 0xA2, (byte) 0xA2, (byte) 0xBC, (byte) 0x20, (byte) 0xB4, (byte) 0x20, (byte) 0x20, (byte) 0xB8, (byte) 0x20, (byte) 0xBA, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xBF, (byte) 0x20, (byte) 0x20, (byte) 0xB3, (byte) 0xB3, (byte) 0xB4, (byte) 0xB5, (byte) 0x20, (byte) 0x20, (byte) 0xB8, (byte) 0x20, (byte) 0xBA, (byte) 0x20, (byte) 0xBC, (byte) 0xBE, (byte) 0xBE, (byte) 0xBF, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0xF0, (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB, (byte) 0xFC, (byte) 0xFD, (byte) 0xFE, (byte) 0xFF, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0xF0, (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB, (byte) 0xFC, (byte) 0xFD, (byte) 0xFE, (byte) 0xFF, }; @Override public String getName() { return "windows-1251"; } @Override public String getLanguage() { return "ru"; } @Override public CharsetMatch match(CharsetDetector det) { int confidence = match(det, ngrams, byteMap); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } } static class CharsetRecog_windows_1256 extends CharsetRecog_sbcs { private static int[] ngrams = { 0x20C7E1, 0x20C7E4, 0x20C8C7, 0x20DAE1, 0x20DDED, 0x20E1E1, 0x20E3E4, 0x20E6C7, 0xC720C7, 0xC7C120, 0xC7CA20, 0xC7D120, 0xC7E120, 0xC7E1C3, 0xC7E1C7, 0xC7E1C8, 0xC7E1CA, 0xC7E1CC, 0xC7E1CD, 0xC7E1CF, 0xC7E1D3, 0xC7E1DA, 0xC7E1DE, 0xC7E1E3, 0xC7E1E6, 0xC7E1ED, 0xC7E320, 0xC7E420, 0xC7E4CA, 0xC820C7, 0xC920C7, 0xC920DD, 0xC920E1, 0xC920E3, 0xC920E6, 0xCA20C7, 0xCF20C7, 0xCFC920, 0xD120C7, 0xD1C920, 0xD320C7, 0xDA20C7, 0xDAE1EC, 0xDDED20, 0xE120C7, 0xE1C920, 0xE1EC20, 0xE1ED20, 0xE320C7, 0xE3C720, 0xE3C920, 0xE3E420, 0xE420C7, 0xE520C7, 0xE5C720, 0xE6C7E1, 0xE6E420, 0xEC20C7, 0xED20C7, 0xED20E3, 0xED20E6, 0xEDC920, 0xEDD120, 0xEDE420, }; private static byte[] byteMap = { (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x81, (byte) 0x20, (byte) 0x83, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x88, (byte) 0x20, (byte) 0x8A, (byte) 0x20, (byte) 0x9C, (byte) 0x8D, (byte) 0x8E, (byte) 0x8F, (byte) 0x90, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x98, (byte) 0x20, (byte) 0x9A, (byte) 0x20, (byte) 0x9C, (byte) 0x20, (byte) 0x20, (byte) 0x9F, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xAA, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xB5, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2, (byte) 0xC3, (byte) 0xC4, (byte) 0xC5, (byte) 0xC6, (byte) 0xC7, (byte) 0xC8, (byte) 0xC9, (byte) 0xCA, (byte) 0xCB, (byte) 0xCC, (byte) 0xCD, (byte) 0xCE, (byte) 0xCF, (byte) 0xD0, (byte) 0xD1, (byte) 0xD2, (byte) 0xD3, (byte) 0xD4, (byte) 0xD5, (byte) 0xD6, (byte) 0x20, (byte) 0xD8, (byte) 0xD9, (byte) 0xDA, (byte) 0xDB, (byte) 0xDC, (byte) 0xDD, (byte) 0xDE, (byte) 0xDF, (byte) 0xE0, (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB, (byte) 0xEC, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xF4, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xF9, (byte) 0x20, (byte) 0xFB, (byte) 0xFC, (byte) 0x20, (byte) 0x20, (byte) 0xFF, }; @Override public String getName() { return "windows-1256"; } @Override public String getLanguage() { return "ar"; } @Override public CharsetMatch match(CharsetDetector det) { int confidence = match(det, ngrams, byteMap); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } } static class CharsetRecog_KOI8_R extends CharsetRecog_sbcs { private static int[] ngrams = { 0x20C4CF, 0x20C920, 0x20CBC1, 0x20CBCF, 0x20CEC1, 0x20CEC5, 0x20CFC2, 0x20D0CF, 0x20D0D2, 0x20D2C1, 0x20D3CF, 0x20D3D4, 0x20D4CF, 0x20D720, 0x20D7CF, 0x20DAC1, 0x20DCD4, 0x20DED4, 0xC1CEC9, 0xC1D4D8, 0xC5CCD8, 0xC5CEC9, 0xC5D3D4, 0xC5D420, 0xC7CF20, 0xC920D0, 0xC9C520, 0xC9C920, 0xC9D120, 0xCCC5CE, 0xCCC920, 0xCCD8CE, 0xCEC120, 0xCEC520, 0xCEC9C5, 0xCEC9D1, 0xCECF20, 0xCECFD7, 0xCF20D0, 0xCF20D3, 0xCF20D7, 0xCFC7CF, 0xCFCA20, 0xCFCCD8, 0xCFCD20, 0xCFD3D4, 0xCFD720, 0xCFD7C1, 0xD0CFCC, 0xD0D2C5, 0xD0D2C9, 0xD0D2CF, 0xD2C1D7, 0xD2C5C4, 0xD3D120, 0xD3D4C1, 0xD3D4C9, 0xD3D4D7, 0xD4C5CC, 0xD4CF20, 0xD4CFD2, 0xD4D820, 0xD9C820, 0xDED4CF, }; private static byte[] byteMap = { (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x00, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x6A, (byte) 0x6B, (byte) 0x6C, (byte) 0x6D, (byte) 0x6E, (byte) 0x6F, (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x7A, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xA3, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xA3, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2, (byte) 0xC3, (byte) 0xC4, (byte) 0xC5, (byte) 0xC6, (byte) 0xC7, (byte) 0xC8, (byte) 0xC9, (byte) 0xCA, (byte) 0xCB, (byte) 0xCC, (byte) 0xCD, (byte) 0xCE, (byte) 0xCF, (byte) 0xD0, (byte) 0xD1, (byte) 0xD2, (byte) 0xD3, (byte) 0xD4, (byte) 0xD5, (byte) 0xD6, (byte) 0xD7, (byte) 0xD8, (byte) 0xD9, (byte) 0xDA, (byte) 0xDB, (byte) 0xDC, (byte) 0xDD, (byte) 0xDE, (byte) 0xDF, (byte) 0xC0, (byte) 0xC1, (byte) 0xC2, (byte) 0xC3, (byte) 0xC4, (byte) 0xC5, (byte) 0xC6, (byte) 0xC7, (byte) 0xC8, (byte) 0xC9, (byte) 0xCA, (byte) 0xCB, (byte) 0xCC, (byte) 0xCD, (byte) 0xCE, (byte) 0xCF, (byte) 0xD0, (byte) 0xD1, (byte) 0xD2, (byte) 0xD3, (byte) 0xD4, (byte) 0xD5, (byte) 0xD6, (byte) 0xD7, (byte) 0xD8, (byte) 0xD9, (byte) 0xDA, (byte) 0xDB, (byte) 0xDC, (byte) 0xDD, (byte) 0xDE, (byte) 0xDF, }; @Override public String getName() { return "KOI8-R"; } @Override public String getLanguage() { return "ru"; } @Override public CharsetMatch match(CharsetDetector det) { int confidence = match(det, ngrams, byteMap); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } } abstract static class CharsetRecog_IBM424_he extends CharsetRecog_sbcs { protected static byte[] byteMap = { /* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F */ /* 0- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 1- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 2- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 3- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 4- */ (byte) 0x40, (byte) 0x41, (byte) 0x42, (byte) 0x43, (byte) 0x44, (byte) 0x45, (byte) 0x46, (byte) 0x47, (byte) 0x48, (byte) 0x49, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 5- */ (byte) 0x40, (byte) 0x51, (byte) 0x52, (byte) 0x53, (byte) 0x54, (byte) 0x55, (byte) 0x56, (byte) 0x57, (byte) 0x58, (byte) 0x59, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 6- */ (byte) 0x40, (byte) 0x40, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 7- */ (byte) 0x40, (byte) 0x71, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x00, (byte) 0x40, (byte) 0x40, /* 8- */ (byte) 0x40, (byte) 0x81, (byte) 0x82, (byte) 0x83, (byte) 0x84, (byte) 0x85, (byte) 0x86, (byte) 0x87, (byte) 0x88, (byte) 0x89, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 9- */ (byte) 0x40, (byte) 0x91, (byte) 0x92, (byte) 0x93, (byte) 0x94, (byte) 0x95, (byte) 0x96, (byte) 0x97, (byte) 0x98, (byte) 0x99, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* A- */ (byte) 0xA0, (byte) 0x40, (byte) 0xA2, (byte) 0xA3, (byte) 0xA4, (byte) 0xA5, (byte) 0xA6, (byte) 0xA7, (byte) 0xA8, (byte) 0xA9, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* B- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* C- */ (byte) 0x40, (byte) 0x81, (byte) 0x82, (byte) 0x83, (byte) 0x84, (byte) 0x85, (byte) 0x86, (byte) 0x87, (byte) 0x88, (byte) 0x89, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* D- */ (byte) 0x40, (byte) 0x91, (byte) 0x92, (byte) 0x93, (byte) 0x94, (byte) 0x95, (byte) 0x96, (byte) 0x97, (byte) 0x98, (byte) 0x99, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* E- */ (byte) 0x40, (byte) 0x40, (byte) 0xA2, (byte) 0xA3, (byte) 0xA4, (byte) 0xA5, (byte) 0xA6, (byte) 0xA7, (byte) 0xA8, (byte) 0xA9, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* F- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, }; @Override public String getLanguage() { return "he"; } } static class CharsetRecog_IBM424_he_rtl extends CharsetRecog_IBM424_he { @Override public String getName() { return "IBM424_rtl"; } private static int[] ngrams = { 0x404146, 0x404148, 0x404151, 0x404171, 0x404251, 0x404256, 0x404541, 0x404546, 0x404551, 0x404556, 0x404562, 0x404569, 0x404571, 0x405441, 0x405445, 0x405641, 0x406254, 0x406954, 0x417140, 0x454041, 0x454042, 0x454045, 0x454054, 0x454056, 0x454069, 0x454641, 0x464140, 0x465540, 0x465740, 0x466840, 0x467140, 0x514045, 0x514540, 0x514671, 0x515155, 0x515540, 0x515740, 0x516840, 0x517140, 0x544041, 0x544045, 0x544140, 0x544540, 0x554041, 0x554042, 0x554045, 0x554054, 0x554056, 0x554069, 0x564540, 0x574045, 0x584540, 0x585140, 0x585155, 0x625440, 0x684045, 0x685155, 0x695440, 0x714041, 0x714042, 0x714045, 0x714054, 0x714056, 0x714069, }; @Override public CharsetMatch match(CharsetDetector det) { int confidence = match(det, ngrams, byteMap, (byte)0x40); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } } static class CharsetRecog_IBM424_he_ltr extends CharsetRecog_IBM424_he { @Override public String getName() { return "IBM424_ltr"; } private static int[] ngrams = { 0x404146, 0x404154, 0x404551, 0x404554, 0x404556, 0x404558, 0x405158, 0x405462, 0x405469, 0x405546, 0x405551, 0x405746, 0x405751, 0x406846, 0x406851, 0x407141, 0x407146, 0x407151, 0x414045, 0x414054, 0x414055, 0x414071, 0x414540, 0x414645, 0x415440, 0x415640, 0x424045, 0x424055, 0x424071, 0x454045, 0x454051, 0x454054, 0x454055, 0x454057, 0x454068, 0x454071, 0x455440, 0x464140, 0x464540, 0x484140, 0x514140, 0x514240, 0x514540, 0x544045, 0x544055, 0x544071, 0x546240, 0x546940, 0x555151, 0x555158, 0x555168, 0x564045, 0x564055, 0x564071, 0x564240, 0x564540, 0x624540, 0x694045, 0x694055, 0x694071, 0x694540, 0x714140, 0x714540, 0x714651 }; @Override public CharsetMatch match(CharsetDetector det) { int confidence = match(det, ngrams, byteMap, (byte)0x40); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } } abstract static class CharsetRecog_IBM420_ar extends CharsetRecog_sbcs { protected static byte[] byteMap = { /* -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F */ /* 0- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 1- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 2- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 3- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 4- */ (byte) 0x40, (byte) 0x40, (byte) 0x42, (byte) 0x43, (byte) 0x44, (byte) 0x45, (byte) 0x46, (byte) 0x47, (byte) 0x48, (byte) 0x49, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 5- */ (byte) 0x40, (byte) 0x51, (byte) 0x52, (byte) 0x40, (byte) 0x40, (byte) 0x55, (byte) 0x56, (byte) 0x57, (byte) 0x58, (byte) 0x59, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 6- */ (byte) 0x40, (byte) 0x40, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67, (byte) 0x68, (byte) 0x69, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 7- */ (byte) 0x70, (byte) 0x71, (byte) 0x72, (byte) 0x73, (byte) 0x74, (byte) 0x75, (byte) 0x76, (byte) 0x77, (byte) 0x78, (byte) 0x79, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, /* 8- */ (byte) 0x80, (byte) 0x81, (byte) 0x82, (byte) 0x83, (byte) 0x84, (byte) 0x85, (byte) 0x86, (byte) 0x87, (byte) 0x88, (byte) 0x89, (byte) 0x8A, (byte) 0x8B, (byte) 0x8C, (byte) 0x8D, (byte) 0x8E, (byte) 0x8F, /* 9- */ (byte) 0x90, (byte) 0x91, (byte) 0x92, (byte) 0x93, (byte) 0x94, (byte) 0x95, (byte) 0x96, (byte) 0x97, (byte) 0x98, (byte) 0x99, (byte) 0x9A, (byte) 0x9B, (byte) 0x9C, (byte) 0x9D, (byte) 0x9E, (byte) 0x9F, /* A- */ (byte) 0xA0, (byte) 0x40, (byte) 0xA2, (byte) 0xA3, (byte) 0xA4, (byte) 0xA5, (byte) 0xA6, (byte) 0xA7, (byte) 0xA8, (byte) 0xA9, (byte) 0xAA, (byte) 0xAB, (byte) 0xAC, (byte) 0xAD, (byte) 0xAE, (byte) 0xAF, /* B- */ (byte) 0xB0, (byte) 0xB1, (byte) 0xB2, (byte) 0xB3, (byte) 0xB4, (byte) 0xB5, (byte) 0x40, (byte) 0x40, (byte) 0xB8, (byte) 0xB9, (byte) 0xBA, (byte) 0xBB, (byte) 0xBC, (byte) 0xBD, (byte) 0xBE, (byte) 0xBF, /* C- */ (byte) 0x40, (byte) 0x81, (byte) 0x82, (byte) 0x83, (byte) 0x84, (byte) 0x85, (byte) 0x86, (byte) 0x87, (byte) 0x88, (byte) 0x89, (byte) 0x40, (byte) 0xCB, (byte) 0x40, (byte) 0xCD, (byte) 0x40, (byte) 0xCF, /* D- */ (byte) 0x40, (byte) 0x91, (byte) 0x92, (byte) 0x93, (byte) 0x94, (byte) 0x95, (byte) 0x96, (byte) 0x97, (byte) 0x98, (byte) 0x99, (byte) 0xDA, (byte) 0xDB, (byte) 0xDC, (byte) 0xDD, (byte) 0xDE, (byte) 0xDF, /* E- */ (byte) 0x40, (byte) 0x40, (byte) 0xA2, (byte) 0xA3, (byte) 0xA4, (byte) 0xA5, (byte) 0xA6, (byte) 0xA7, (byte) 0xA8, (byte) 0xA9, (byte) 0xEA, (byte) 0xEB, (byte) 0x40, (byte) 0xED, (byte) 0xEE, (byte) 0xEF, /* F- */ (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0x40, (byte) 0xFB, (byte) 0xFC, (byte) 0xFD, (byte) 0xFE, (byte) 0x40, }; @Override public String getLanguage() { return "ar"; } } static class CharsetRecog_IBM420_ar_rtl extends CharsetRecog_IBM420_ar { private static int[] ngrams = { 0x4056B1, 0x4056BD, 0x405856, 0x409AB1, 0x40ABDC, 0x40B1B1, 0x40BBBD, 0x40CF56, 0x564056, 0x564640, 0x566340, 0x567540, 0x56B140, 0x56B149, 0x56B156, 0x56B158, 0x56B163, 0x56B167, 0x56B169, 0x56B173, 0x56B178, 0x56B19A, 0x56B1AD, 0x56B1BB, 0x56B1CF, 0x56B1DC, 0x56BB40, 0x56BD40, 0x56BD63, 0x584056, 0x624056, 0x6240AB, 0x6240B1, 0x6240BB, 0x6240CF, 0x634056, 0x734056, 0x736240, 0x754056, 0x756240, 0x784056, 0x9A4056, 0x9AB1DA, 0xABDC40, 0xB14056, 0xB16240, 0xB1DA40, 0xB1DC40, 0xBB4056, 0xBB5640, 0xBB6240, 0xBBBD40, 0xBD4056, 0xBF4056, 0xBF5640, 0xCF56B1, 0xCFBD40, 0xDA4056, 0xDC4056, 0xDC40BB, 0xDC40CF, 0xDC6240, 0xDC7540, 0xDCBD40, }; @Override public String getName() { return "IBM420_rtl"; } @Override public CharsetMatch match(CharsetDetector det) { int confidence = matchIBM420(det, ngrams, byteMap, (byte)0x40); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } } static class CharsetRecog_IBM420_ar_ltr extends CharsetRecog_IBM420_ar { private static int[] ngrams = { 0x404656, 0x4056BB, 0x4056BF, 0x406273, 0x406275, 0x4062B1, 0x4062BB, 0x4062DC, 0x406356, 0x407556, 0x4075DC, 0x40B156, 0x40BB56, 0x40BD56, 0x40BDBB, 0x40BDCF, 0x40BDDC, 0x40DAB1, 0x40DCAB, 0x40DCB1, 0x49B156, 0x564056, 0x564058, 0x564062, 0x564063, 0x564073, 0x564075, 0x564078, 0x56409A, 0x5640B1, 0x5640BB, 0x5640BD, 0x5640BF, 0x5640DA, 0x5640DC, 0x565840, 0x56B156, 0x56CF40, 0x58B156, 0x63B156, 0x63BD56, 0x67B156, 0x69B156, 0x73B156, 0x78B156, 0x9AB156, 0xAB4062, 0xADB156, 0xB14062, 0xB15640, 0xB156CF, 0xB19A40, 0xB1B140, 0xBB4062, 0xBB40DC, 0xBBB156, 0xBD5640, 0xBDBB40, 0xCF4062, 0xCF40DC, 0xCFB156, 0xDAB19A, 0xDCAB40, 0xDCB156 }; @Override public String getName() { return "IBM420_ltr"; } @Override public CharsetMatch match(CharsetDetector det) { int confidence = matchIBM420(det, ngrams, byteMap, (byte)0x40); return confidence == 0 ? null : new CharsetMatch(det, this, confidence); } } } ================================================ FILE: src/main/java/com/ibm/icu/text/CharsetRecognizer.java ================================================ // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /** ******************************************************************************* * Copyright (C) 2005-2012, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* */ package com.ibm.icu.text; /** * Abstract class for recognizing a single charset. * Part of the implementation of ICU's CharsetDetector. * * Each specific charset that can be recognized will have an instance * of some subclass of this class. All interaction between the overall * CharsetDetector and the stuff specific to an individual charset happens * via the interface provided here. * * Instances of CharsetDetector DO NOT have or maintain * state pertaining to a specific match or detect operation. * The WILL be shared by multiple instances of CharsetDetector. * They encapsulate const charset-specific information. */ abstract class CharsetRecognizer { /** * Get the IANA name of this charset. * @return the charset name. */ abstract String getName(); /** * Get the ISO language code for this charset. * @return the language code, or null if the language cannot be determined. */ public String getLanguage() { return null; } /** * Test the match of this charset with the input text data * which is obtained via the CharsetDetector object. * * @param det The CharsetDetector, which contains the input text * to be checked for being in this charset. * @return A CharsetMatch object containing details of match * with this charset, or null if there was no match. */ abstract CharsetMatch match(CharsetDetector det); } ================================================ FILE: src/main/java/org/billthefarmer/editor/Editor.java ================================================ /////////////////////////////////////////////////////////////////////////////// // // Editor - Text editor for Android // // Copyright © 2017 Bill Farmer // // 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 . // // Bill Farmer william j farmer [at] yahoo [dot] co [dot] uk. // //////////////////////////////////////////////////////////////////////////////// package org.billthefarmer.editor; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.Typeface; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.print.PrintAttributes; import android.print.PrintDocumentAdapter; import android.print.PrintManager; import android.text.Editable; import android.text.Html; import android.text.InputType; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextPaint; import android.text.TextUtils; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; import android.text.style.BackgroundColorSpan; import android.text.style.ForegroundColorSpan; import android.util.Log; import android.view.ActionMode; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.SearchView; import android.widget.SeekBar; import android.widget.TextView; import android.support.v4.content.FileProvider; import com.ibm.icu.text.CharsetDetector; import com.ibm.icu.text.CharsetMatch; import org.commonmark.node.*; import org.commonmark.parser.Parser; import org.commonmark.renderer.html.HtmlRenderer; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.nio.charset.Charset; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.regex.Matcher; import java.util.regex.Pattern; @SuppressWarnings("deprecation") public class Editor extends Activity { public final static String TAG = "Editor"; public final static String PATH = "path"; public final static String EDIT = "edit"; public final static String MATCH = "match"; public final static String CHANGED = "changed"; public final static String CONTENT = "content"; public final static String MODIFIED = "modified"; public final static String MONOSPACE = "monospace"; public final static String PREF_FILE = "pref_file"; public final static String PREF_HIGH = "pref_high"; public final static String PREF_PATHS = "pref_paths"; public final static String PREF_SAVE = "pref_save"; public final static String PREF_LAST = "pref_last"; public final static String PREF_VIEW = "pref_view"; public final static String PREF_SIZE = "pref_size"; public final static String PREF_SUGGEST = "pref_suggest"; public final static String PREF_THEME = "pref_theme"; public final static String PREF_TYPE = "pref_type"; public final static String PREF_WRAP = "pref_wrap"; public final static String DOCUMENTS = "Documents"; public final static String FOLDER = "Folder"; public final static String UTF_8 = "UTF-8"; public final static String NEW_FILE = "Untitled.txt"; public final static String EDIT_FILE = "Editor.txt"; public final static String HTML_FILE = "Editor.html"; public final static String TEXT_HTML = "text/html"; public final static String TEXT_PLAIN = "text/plain"; public final static String TEXT_WILD = "text/*"; public final static Pattern PATTERN_CHARS = Pattern.compile("[\\(\\)\\[\\]\\{\\}\\<\\>\"'`]"); public final static String BRACKET_CHARS = "([{<"; public final static String HTML_HEAD = "\n\n\n\n" + "\n\n\n"; public final static String HTML_TAIL = "\n\n\n"; public final static String FILE_PROVIDER = "org.billthefarmer.editor.fileprovider"; public final static String OPEN_NEW = "org.billthefarmer.editor.OPEN_NEW"; public final static String PACKAGE = "package:"; public final static String CC_EXT = "\\.(c(c|pp|xx|\\+\\+)?|dart|go|h|java|js|kt|m|py|swift|rs)"; public final static String HTML_EXT = "\\.html?"; public final static String CSS_EXT = "\\.css?"; public final static String ORG_EXT = "\\.org"; public final static String MD_EXT = "\\.md"; public final static String SH_EXT = "\\.sh"; // Syntax patterns public final static Pattern KEYWORDS = Pattern.compile ("\\b(abstract|and|arguments|as(m|sert|sociativity|ync)?|await|auto|" + "base|break|" + "case|catch|chan|char|class|con(st|tinue|venience)|continue|" + "covariant|crate|" + "de(bugger|f|fault|fer|fered|in|init|l|lete)|didset|do(ne)?|" + "dyn(amic)?" + "(type)?|el(if|se)|enum|esac|eval|ex(cept|ec|plicit|port|" + "tends|tension|tern)|factory|fal(lthrough|se)|fi(nal|nally)?|fn|for|" + "friend|from|fun(c(tion)?)?|get|global|go(to)?|hide|if|" + "im(pl|plements|port)|in(fix|it|line|out|stanceof|terface|" + "ternal)?|is|la(mbda|te|zy)|left|let|library|lo(cal|oop)|ma(p|" + "tch)|mut(able|ating)|" + "namespace|native|new|nil|none|nonmutating|not|null|of|on|" + "operator|optional|or|override|package|part|pass|postfix|" + "pre(cedence|fix)|print|private|prot(ected|ocol)|pub(lic)?|" + "raise|range|re(f|gister|quired|throw|turn)|right|se(lect|aled|lf)|" + "set|show|signed|sizeof|static|strictfp|struct|subscript|super|" + "switch|sync(hronized)?|template|th(en|is|rows?)|transient|" + "true|try|type(alias|def|id|name|of)?|un(ion|owned|safe|signed)|" + "us(e|ing)|va(l|r)|virtual|void|volatile|weak|wh(en|ere|ile)|" + "willset|with|yield)\\b", Pattern.MULTILINE); public final static Pattern TYPES = Pattern.compile ("\\b(j?bool(ean)?|(u|j)?(byte|char|double|float|int(eger)?|" + "long|short))\\b", Pattern.MULTILINE); public final static Pattern ANNOTATION = Pattern.compile("@\\b[A-Za-z]+\\b", Pattern.MULTILINE); public final static Pattern CC_COMMENT = Pattern.compile ("//.*$|(\"(?:\\\\[^\"]|\\\\\"|.)*?\")|(?s)/\\*.*?\\*/", Pattern.MULTILINE); public final static Pattern CLASS = Pattern.compile ("\\b[A-Z][A-Za-z0-9_]+\\b", Pattern.MULTILINE); public final static Pattern CONSTANT = Pattern.compile ("\\b(([A-Z][A-Z0-9_]+)|(k[A-Z][A-Za-z0-9]+))\\b", Pattern.MULTILINE); public final static Pattern OPERATOR = Pattern.compile ("[+-=:;<>|!%^&*/?]+", Pattern.MULTILINE); public final static Pattern NUMBER = Pattern.compile ("\\b\\d+(\\.\\d*)?(e(\\+|\\-)?\\d+)?\\b", Pattern.MULTILINE); public final static Pattern QUOTED = Pattern.compile // "'([^\\\\']+|\\\\([btnfr\"'\\\\]|" + // "[0-3]?[0-7]{1,2}|u[0-9a-fA-F]{4}))*'|" + ("\"([^\\\\\"]+|\\\\([btnfr\"'\\\\]|" + "[0-3]?[0-7]{1,2}|u[0-9a-fA-F]{4}))*\"", Pattern.MULTILINE); public final static Pattern HTML_TAGS = Pattern.compile ("\\b(html|base|head|link|meta|style|title|body|address|article|" + "aside|footer|header|h\\d|hgroup|main|nav|section|blockquote|dd|" + "dir|div|dl|dt|figcaption|figure|hr|li|main|ol|p|pre|ul|a|abbr|" + "b|bdi|bdo|br|cite|code|data|dfn|em|i|kbd|mark|q|rb|rp|rt|rtc|" + "ruby|s|samp|small|span|strong|sub|sup|time|tt|u|var|wbr|area|" + "audio|img|map|track|video|applet|embed|iframe|noembed|object|" + "param|picture|source|canvas|noscript|script|del|ins|caption|" + "col|colgroup|table|tbody|td|tfoot|th|thead|tr|button|datalist|" + "fieldset|form|input|label|legend|meter|optgroup|option|output|" + "progress|select|textarea|details|dialog|menu|menuitem|summary|" + "content|element|shadow|slot|template|acronym|applet|basefont|" + "bgsound|big|blink|center|command|content|dir|element|font|" + "frame|frameset|image|isindex|keygen|listing|marquee|menuitem|" + "multicol|nextid|nobr|noembed|noframes|plaintext|shadow|spacer|" + "strike|tt|xmp|doctype)\\b", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); public final static Pattern HTML_ATTRS = Pattern.compile ("\\b(accept|accesskey|action|align|allow|alt|async|" + "auto(capitalize|complete|focus|play)|background|" + "bgcolor|border|buffered|challenge|charset|checked|cite|" + "class|code(base)?|color|cols|colspan|content(" + "editable)?|contextmenu|controls|coords|crossorigin|" + "csp|data|datetime|decoding|def(ault|er)|dir|dirname|" + "disabled|download|draggable|dropzone|enctype|enterkeyhint|" + "equiv|for|form(action|novalidate)?|headers|height|" + "hidden|high|href(lang)?|http|icon|id|importance|" + "inputmode|integrity|intrinsicsize|ismap|itemprop|keytype|" + "kind|label|lang|language|list|loading|loop|low|manifest|" + "max|maxlength|media|method|min|minlength|multiple|muted|" + "name|novalidate|open|optimum|pattern|ping|placeholder|" + "poster|preload|property|radiogroup|readonly|referrerpolicy|" + "rel|required|reversed|rows|rowspan|sandbox|scope|scoped|" + "selected|shape|size|sizes|slot|span|spellcheck|src|srcdoc|" + "srclang|srcset|start|step|style|summary|tabindex|target|" + "title|translate|type|usemap|value|width|wrap)\\b", Pattern.MULTILINE); public final static Pattern HTML_COMMENT = Pattern.compile("", Pattern.MULTILINE); public final static Pattern CSS_STYLES = Pattern.compile ("\\b(action|active|additive|adjust|after|align|all|alternates|" + "animation|annotation|area|areas|as|asian|attachment|attr|" + "auto|backdrop|backface|background|basis|before|behavior|" + "bezier|bidi|blend|block|blur|border|both|bottom|box|break|" + "brightness|calc|caps|caption|caret|cells|center|ch|change|" + "character|charset|checked|child|circle|clamp|clear|clip|" + "cm|collapse|color|column|columns|combine|composite|conic|" + "content|contrast|count|counter|counters|cross|cubic|cue|" + "cursor|decoration|default|deg|delay|dir|direction|" + "disabled|display|dpcm|dpi|dppx|drop|duration|east|element|" + "ellipse|em|emphasis|empty|enabled|end|env|events|ex|face|" + "fade|fallback|family|feature|fill|filter|first|fit|flex|" + "float|flow|focus|font|format|forms|fr|frames|fullscreen|" + "function|gap|grad|gradient|grayscale|grid|grow|hanging|" + "height|historical|hover|hsl|hsla|hue|hyphens|hz|image|import|" + "in|increment|indent|indeterminate|index|inherit|initial|" + "inline|inset|inside|invalid|invert|isolation|items|" + "iteration|justify|khz|kerning|keyframes|lang|language|" + "last|layout|leader|left|letter|ligatures|line|linear|link|" + "list|local|margin|mask|matrix|matrix3d|max|media|min|" + "minmax|mix|mm|mode|ms|name|namespace|negative|none|not|nth|" + "numeric|object|of|offset|only|opacity|optical|optional|" + "order|orientation|origin|ornaments|orphans|out|outline|" + "outset|outside|overflow|override|pad|padding|page|path|pc|" + "perspective|place|placeholder|play|pointer|polygon|" + "position|prefix|property|pt|punctuation|px|q|quotes|rad|" + "radial|radius|range|read|rect|relative|rem|rendering|repeat|" + "repeating|required|reset|resize|revert|rgb|rgba|right|" + "root|rotate|rotate3d|rotatex|rotatey|rotatez|row|rows|" + "rule|s|saturate|scale|scale3d|scalex|scaley|scalez|scope|" + "scroll|scrollbar|selection|self|sepia|set|settings|shadow|" + "shape|shrink|side|size|sizing|skew|skewx|skewy|slice|" + "slotted|snap|source|space|spacing|span|speak|src|start|" + "state|static|steps|stop|stretch|style|styleset|stylistic|suffix|" + "supports|swash|symbols|synthesis|system|tab|table|target|" + "template|text|threshold|timing|top|touch|transform|" + "transition|translate|translate3d|translatex|translatey|" + "translatez|turn|type|underline|unicode|unset|upright|url|" + "user|valid|values|var|variant|variation|vertical|vh|" + "viewport|visibility|visited|vmax|vmin|vw|weight|white|" + "widows|width|will|word|wrap|write|writing|x|y|z|zoom)\\b", Pattern.MULTILINE); public final static Pattern CSS_HEX = Pattern.compile ("#\\b[A-Fa-f0-9]+\\b", Pattern.MULTILINE); public final static Pattern ORG_HEADER = Pattern.compile ("(^\\*+ +.+$)|(^#\\+.+$)", Pattern.MULTILINE); public final static Pattern ORG_LINK = Pattern.compile ("\\[\\[.*?\\]\\]", Pattern.MULTILINE); public final static Pattern ORG_EMPH = Pattern.compile ("(([*~/+=]+)\\b(\\w| )+?\\b\\2)|(\\b(_{1,2})(\\w| )+?\\5\\b)", Pattern.MULTILINE); public final static Pattern ORG_COMMENT = Pattern.compile ("(^# .*$)|(@@.*?@@)", Pattern.MULTILINE); public final static Pattern MD_HEADER = Pattern.compile ("(^.+\\s+-+$)|(^.+\\s+=+$)|(^#+ +.+$)", Pattern.MULTILINE); public final static Pattern MD_LINK = Pattern.compile ("(\\!?\\[.+\\] *\\(.+\\))|(!?\\[.+\\] *\\[.+\\])|" + "( *\\[.+\\]: +.+$)", Pattern.MULTILINE); public final static Pattern MD_EMPH = Pattern.compile ("(([*~]{1,2})\\b(\\w| )+?\\b\\2)|(\\b(_{1,2})(\\w| )+?\\5\\b)", Pattern.MULTILINE); public final static Pattern MD_CODE = Pattern.compile ("(^ {4,}.+$)|(`.+?`)", Pattern.MULTILINE); public final static Pattern SH_VAR = Pattern.compile ("(\\$\\b\\w+\\b)|(\\$\\{.+?\\})|(\\$\\(.+?\\))", Pattern.MULTILINE); public final static Pattern SH_COMMENT = Pattern.compile ("#.*$", Pattern.MULTILINE); public final static Pattern MODE_PATTERN = Pattern.compile ("^\\S+\\s+ed:(.+)$", Pattern.MULTILINE); public final static Pattern OPTION_PATTERN = Pattern.compile ("(\\s+(no)?(vw|ww|sg|cs|hs|th|ts|tf)(:\\w)?)", Pattern.MULTILINE); public final static Pattern WORD_PATTERN = Pattern.compile ("\\w+", Pattern.MULTILINE); public final static int LAST_SIZE = 256; public final static int MENU_SIZE = 192; public final static int FIRST_SIZE = 256; public final static int TOO_LARGE = 524288; public final static int FOLDER_OFFSET = 0x7d000000; public final static int POSITION_DELAY = 128; public final static int UPDATE_DELAY = 128; public final static int FIND_DELAY = 128; public final static int MAX_PATHS = 10; public final static int REQUEST_OPEN = 1; public final static int OPEN_DOCUMENT = 1; public final static int CREATE_DOCUMENT = 2; public final static int LIGHT = 1; public final static int DARK = 2; public final static int SYSTEM = 3; public final static int WHITE = 4; public final static int BLACK = 5; public final static int RETRO = 6; private final static int TINY = 8; private final static int SMALL = 12; private final static int MEDIUM = 18; private final static int LARGE = 24; private final static int HUGE = 32; private final static int NORMAL = 1; private final static int MONO = 2; private final static int SANS = 3; private final static int SERIF = 4; private final static int NO_SYNTAX = 0; private final static int CC_SYNTAX = 1; private final static int HTML_SYNTAX = 2; private final static int CSS_SYNTAX = 3; private final static int ORG_SYNTAX = 4; private final static int MD_SYNTAX = 5; private final static int SH_SYNTAX = 6; private final static int DEF_SYNTAX = 7; private Uri uri; private File file; private String path; private Uri content; private String match; private EditText textView; private TextView customView; private MenuItem searchItem; private SearchView searchView; private ScrollView scrollView; private Runnable updateHighlight; private Runnable updateWordCount; private ScaleGestureDetector scaleDetector; private QueryTextListener queryTextListener; private ExecutorService executor; private Map pathMap; private List removeList; private boolean highlight = false; private boolean last = false; private boolean save = false; private boolean edit = false; private boolean view = false; private boolean wrap = false; private boolean suggest = true; private boolean changed = false; private long modified; private int theme = LIGHT; private int size = MEDIUM; private int type = MONO; private int syntax; // onCreate @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String typefaces[] = getResources().getStringArray(R.array.typefaces); List typeList = Arrays.asList(typefaces); int monospace = typeList.indexOf(MONOSPACE); save = preferences.getBoolean(PREF_SAVE, false); view = preferences.getBoolean(PREF_VIEW, true); last = preferences.getBoolean(PREF_LAST, false); wrap = preferences.getBoolean(PREF_WRAP, false); suggest = preferences.getBoolean(PREF_SUGGEST, true); highlight = preferences.getBoolean(PREF_HIGH, false); theme = preferences.getInt(PREF_THEME, LIGHT); size = preferences.getInt(PREF_SIZE, MEDIUM); type = preferences.getInt(PREF_TYPE, monospace); Set pathSet = preferences.getStringSet(PREF_PATHS, null); pathMap = new HashMap<>(); if (pathSet != null) for (String path : pathSet) pathMap.put(path, preferences.getInt(path, 0)); removeList = new ArrayList<>(); Configuration config = getResources().getConfiguration(); int night = config.uiMode & Configuration.UI_MODE_NIGHT_MASK; switch (theme) { case LIGHT: setTheme(R.style.AppTheme); break; case DARK: setTheme(R.style.AppDarkTheme); break; case SYSTEM: switch (night) { case Configuration.UI_MODE_NIGHT_NO: setTheme(R.style.AppTheme); break; case Configuration.UI_MODE_NIGHT_YES: setTheme(R.style.AppDarkTheme); break; } break; case WHITE: setTheme(R.style.AppWhiteTheme); break; case BLACK: setTheme(R.style.AppBlackTheme); break; case RETRO: setTheme(R.style.AppRetroTheme); break; } if (wrap) setContentView(R.layout.wrap); else setContentView(R.layout.edit); textView = findViewById(R.id.text); scrollView = findViewById(R.id.vscroll); getActionBar().setSubtitle(match); getActionBar().setCustomView(R.layout.custom); getActionBar().setDisplayShowCustomEnabled(true); customView = (TextView) getActionBar().getCustomView(); updateWordCount = () -> wordCountText(); if (savedInstanceState != null) edit = savedInstanceState.getBoolean(EDIT); if (!edit) { textView.setRawInputType(InputType.TYPE_NULL); textView.setTextIsSelectable(true); } else if (!suggest) textView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); setSizeAndTypeface(size, type); executor = Executors.newSingleThreadExecutor(); setListeners(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) { alertDialog(this, R.string.access, R.string.manageFiles, R.string.access, R.string.cancel, (dialog, id) -> { switch (id) { case DialogInterface.BUTTON_POSITIVE: Uri appId = Uri.parse(PACKAGE + BuildConfig.APPLICATION_ID); Intent intent = new Intent(android.provider.Settings. ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, appId); startActivity(intent); break; case DialogInterface.BUTTON_NEGATIVE: break; } }); newFile(); return; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { alertDialog(this, R.string.files, R.string.manageFiles, R.string.files, R.string.cancel, (dialog, id) -> { switch (id) { case DialogInterface.BUTTON_POSITIVE: requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_OPEN); break; case DialogInterface.BUTTON_NEGATIVE: break; } }); newFile(); return; } Intent intent = getIntent(); Uri uri = intent.getData(); switch (intent.getAction()) { case Intent.ACTION_EDIT: case Intent.ACTION_VIEW: if ((savedInstanceState == null) && (uri != null)) readFile(uri); getActionBar().setDisplayHomeAsUpEnabled(true); break; case Intent.ACTION_SEND: if (savedInstanceState == null) { // Get uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM); // Get text String text = intent.getStringExtra(Intent.EXTRA_TEXT); if (uri != null) readFile(uri); else if (text != null) { newFile(text); changed = true; } else defaultFile(); } break; case OPEN_NEW: if (savedInstanceState == null) { newFile(); textView.postDelayed(() -> editClicked(null), UPDATE_DELAY); } break; case Intent.ACTION_MAIN: if (savedInstanceState == null) { if (last) lastFile(); else defaultFile(); } break; } } // setListeners private void setListeners() { scaleDetector = new ScaleGestureDetector(this, new ScaleListener()); queryTextListener = new QueryTextListener(); if (textView != null) { textView.addTextChangedListener(new TextWatcher() { // afterTextChanged @Override public void afterTextChanged(Editable s) { if (!changed) { changed = true; invalidateOptionsMenu(); } if (updateHighlight != null) { textView.removeCallbacks(updateHighlight); textView.postDelayed(updateHighlight, UPDATE_DELAY); } if (updateWordCount != null) { textView.removeCallbacks(updateWordCount); textView.postDelayed(updateWordCount, UPDATE_DELAY); } } // beforeTextChanged @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (searchItem != null && searchItem.isActionViewExpanded()) { final CharSequence query = searchView.getQuery(); textView.postDelayed(() -> { if (searchItem != null && searchItem.isActionViewExpanded()) { if (query != null) searchView.setQuery(query, false); } }, UPDATE_DELAY); } } // onTextChanged @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} }); // onFocusChange textView.setOnFocusChangeListener((v, hasFocus) -> { // Hide keyboard InputMethodManager manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); if (!hasFocus) manager.hideSoftInputFromWindow(v.getWindowToken(), 0); if (updateHighlight != null) { textView.removeCallbacks(updateHighlight); textView.postDelayed(updateHighlight, UPDATE_DELAY); } }); // onLongClick textView.setOnLongClickListener(v -> { // Do nothing if already editable if (edit) return false; // Get scroll position int y = scrollView.getScrollY(); // Get height int height = scrollView.getHeight(); // Get width int width = scrollView.getWidth(); // Get offset int line = textView.getLayout() .getLineForVertical(y + height / 2); int offset = textView.getLayout() .getOffsetForHorizontal(line, width / 2); // Set cursor textView.setSelection(offset); // Set editable with or without suggestions if (suggest) textView .setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE); else textView .setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); // Update boolean edit = true; // Restart recreate(this); return false; }); textView.getViewTreeObserver().addOnGlobalLayoutListener(() -> { if (updateHighlight != null) { textView.removeCallbacks(updateHighlight); textView.postDelayed(updateHighlight, UPDATE_DELAY); } }); } if (scrollView != null) { // onScrollChange scrollView.getViewTreeObserver().addOnScrollChangedListener(() -> { if (updateHighlight != null) { textView.removeCallbacks(updateHighlight); textView.postDelayed(updateHighlight, UPDATE_DELAY); } }); } } // onRestoreInstanceState @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); path = savedInstanceState.getString(PATH); edit = savedInstanceState.getBoolean(EDIT); changed = savedInstanceState.getBoolean(CHANGED); match = savedInstanceState.getString(MATCH); modified = savedInstanceState.getLong(MODIFIED); content = savedInstanceState.getParcelable(CONTENT); invalidateOptionsMenu(); file = new File(path); uri = Uri.fromFile(file); if (content != null) setTitle(FileUtils.getDisplayName(this, content, null, null)); else setTitle(uri.getLastPathSegment()); if (match == null) match = UTF_8; getActionBar().setSubtitle(match); checkHighlight(); if (file.lastModified() > modified) alertDialog(this, R.string.appName, R.string.changedReload, R.string.reload, R.string.cancel, (dialog, id) -> { switch (id) { case DialogInterface.BUTTON_POSITIVE: readFile(uri); } }); } // onPause @Override public void onPause() { super.onPause(); // Save current path savePath(path); // Stop highlighting textView.removeCallbacks(updateHighlight); textView.removeCallbacks(updateWordCount); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean(PREF_SAVE, save); editor.putBoolean(PREF_VIEW, view); editor.putBoolean(PREF_LAST, last); editor.putBoolean(PREF_WRAP, wrap); editor.putBoolean(PREF_SUGGEST, suggest); editor.putBoolean(PREF_HIGH, highlight); editor.putInt(PREF_THEME, theme); editor.putInt(PREF_SIZE, size); editor.putInt(PREF_TYPE, type); editor.putString(PREF_FILE, path); // Add the set of recent files editor.putStringSet(PREF_PATHS, pathMap.keySet()); // Add a position for each file for (String path : pathMap.keySet()) editor.putInt(path, pathMap.get(path)); // Remove the old ones for (String path : removeList) editor.remove(path); editor.apply(); // Save file if (changed && save) saveFile(); } // onSaveInstanceState @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(CONTENT, content); outState.putLong(MODIFIED, modified); outState.putBoolean(CHANGED, changed); outState.putString(MATCH, match); outState.putBoolean(EDIT, edit); outState.putString(PATH, path); } // onCreateOptionsMenu @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } // onPrepareOptionsMenu @Override public boolean onPrepareOptionsMenu(Menu menu) { // Set up search view searchItem = menu.findItem(R.id.search); searchView = (SearchView) searchItem.getActionView(); // Set up search view options and listener if (searchView != null) { searchView.setSubmitButtonEnabled(true); searchView.setImeOptions(EditorInfo.IME_ACTION_GO); searchView.setOnQueryTextListener(queryTextListener); } // Show find all item if (menu.findItem(R.id.search).isActionViewExpanded()) menu.findItem(R.id.findAll).setVisible(true); else menu.findItem(R.id.findAll).setVisible(false); menu.findItem(R.id.edit).setVisible(!edit); menu.findItem(R.id.view).setVisible(edit); menu.findItem(R.id.save).setVisible(changed); menu.findItem(R.id.viewFile).setChecked(view); menu.findItem(R.id.openLast).setChecked(last); menu.findItem(R.id.autoSave).setChecked(save); menu.findItem(R.id.wrap).setChecked(wrap); menu.findItem(R.id.suggest).setChecked(suggest); menu.findItem(R.id.highlight).setChecked(highlight); switch (theme) { case LIGHT: menu.findItem(R.id.light).setChecked(true); break; case DARK: menu.findItem(R.id.dark).setChecked(true); break; case SYSTEM: menu.findItem(R.id.system).setChecked(true); break; case WHITE: menu.findItem(R.id.white).setChecked(true); break; case BLACK: menu.findItem(R.id.black).setChecked(true); break; case RETRO: menu.findItem(R.id.retro).setChecked(true); break; } switch (size) { case SMALL: menu.findItem(R.id.small).setChecked(true); break; case MEDIUM: menu.findItem(R.id.medium).setChecked(true); break; case LARGE: menu.findItem(R.id.large).setChecked(true); break; } // Get the charsets Set keySet = Charset.availableCharsets().keySet(); // Get the submenu MenuItem item = menu.findItem(R.id.charset); item.setTitle(match); SubMenu sub = item.getSubMenu(); sub.clear(); // Add charsets contained in both sets sub.add(Menu.NONE, R.id.charsetItem, Menu.NONE, R.string.detect); for (String key: keySet) sub.add(Menu.NONE, R.id.charsetItem, Menu.NONE, key); // Get the typefaces String typefaces[] = getResources().getStringArray(R.array.typefaces); item = menu.findItem(R.id.typeface); sub = item.getSubMenu(); sub.clear(); // Add typefaces for (String typeface: typefaces) sub.add(Menu.NONE, R.id.typefaceItem, Menu.NONE, typeface); sub.getItem(type).setCheckable(true); sub.getItem(type).setChecked(true); // Get a list of recent files List list = new ArrayList<>(); Map map = new HashMap<>(); // Get the last modified dates for (String path: pathMap.keySet()) { File file = new File(path); // Check it exists if (!file.exists()) continue; long last = file.lastModified(); list.add(last); map.put(last, path); } // Sort in reverse order Collections.sort(list); Collections.reverse(list); // Get the submenu item = menu.findItem(R.id.openRecent); sub = item.getSubMenu(); sub.clear(); // Add the recent files for (long date : list) { String path = map.get(date); // Remove path prefix CharSequence name = path.replaceFirst(Environment .getExternalStorageDirectory() .getPath() + File.separator, ""); // Create item sub.add(Menu.NONE, R.id.fileItem, Menu.NONE, TextUtils.ellipsize (name, new TextPaint(), MENU_SIZE, TextUtils.TruncateAt.MIDDLE)) // Use condensed title to save path as API doesn't // work as documented .setTitleCondensed(name); } // Add clear list item sub.add(Menu.NONE, R.id.clearList, Menu.NONE, R.string.clearList); return true; } // onOptionsItemSelected @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); break; case R.id.newFile: newFile(); break; case R.id.edit: editClicked(item); break; case R.id.view: viewClicked(item); break; case R.id.open: openFile(); break; case R.id.save: saveCheck(); break; case R.id.saveAs: saveAs(); break; case R.id.clearList: clearList(); break; case R.id.findAll: findAll(); break; case R.id.goTo: goTo(); break; case R.id.print: print(); break; case R.id.viewMarkdown: viewMarkdown(); break; case R.id.viewFile: viewFileClicked(item); break; case R.id.openLast: openLastClicked(item); break; case R.id.autoSave: autoSaveClicked(item); break; case R.id.wrap: wrapClicked(item); break; case R.id.suggest: suggestClicked(item); break; case R.id.highlight: highlightClicked(item); break; case R.id.light: lightClicked(item); break; case R.id.dark: darkClicked(item); break; case R.id.system: systemClicked(item); break; case R.id.white: whiteClicked(item); break; case R.id.black: blackClicked(item); break; case R.id.retro: retroClicked(item); break; case R.id.small: smallClicked(item); break; case R.id.medium: mediumClicked(item); break; case R.id.large: largeClicked(item); break; case R.id.about: aboutClicked(); break; case R.id.fileItem: openRecent(item); break; case R.id.charsetItem: setCharset(item); break; case R.id.typefaceItem: setTypeface(item); break; } // Close text search if (searchItem != null && searchItem.isActionViewExpanded() && item.getItemId() != R.id.findAll) searchItem.collapseActionView(); return true; } // onBackPressed @Override public void onBackPressed() { // Close text search if (searchItem != null && searchItem.isActionViewExpanded()) { searchItem.collapseActionView(); return; } if (changed) alertDialog(this, R.string.appName, R.string.modified, R.string.save, R.string.discard, (dialog, id) -> { switch (id) { case DialogInterface.BUTTON_POSITIVE: saveFile(); finish(); break; case DialogInterface.BUTTON_NEGATIVE: changed = false; finish(); break; } }); else finish(); } // onActivityResult @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_CANCELED) return; switch (requestCode) { case OPEN_DOCUMENT: content = data.getData(); readFile(content); break; case CREATE_DOCUMENT: content = data.getData(); setTitle(FileUtils.getDisplayName(this, content, null, null)); saveFile(); break; } } // dispatchTouchEvent @Override public boolean dispatchTouchEvent(MotionEvent event) { scaleDetector.onTouchEvent(event); return super.dispatchTouchEvent(event); } // onKeyDown @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Check Ctrl key if (event.isCtrlPressed()) { switch (keyCode) { // Edit, View case KeyEvent.KEYCODE_E: if (event.isShiftPressed()) viewClicked(null); else editClicked(null); break; // Search case KeyEvent.KEYCODE_F: if (event.isShiftPressed()) searchItem.collapseActionView(); else searchItem.expandActionView(); // Find next if (event.isAltPressed() && searchItem.isActionViewExpanded()) queryTextListener.onQueryTextSubmit (searchView.getQuery().toString()); break; // Goto case KeyEvent.KEYCODE_G: goTo(); break; // Menu case KeyEvent.KEYCODE_M: openOptionsMenu(); break; // New case KeyEvent.KEYCODE_N: newFile(); break; // Open case KeyEvent.KEYCODE_O: openFile(); break; // Print case KeyEvent.KEYCODE_P: print(); break; // Save, Save as case KeyEvent.KEYCODE_S: if (event.isShiftPressed()) saveAs(); else saveCheck(); break; // Increase text size case KeyEvent.KEYCODE_PLUS: case KeyEvent.KEYCODE_EQUALS: size += 2; size = Math.max(TINY, Math.min(size, HUGE)); textView.setTextSize(size); break; // Decrease text size case KeyEvent.KEYCODE_MINUS: size -= 2; size = Math.max(TINY, Math.min(size, HUGE)); textView.setTextSize(size); break; default: return super.onKeyDown(keyCode, event); } return true; } else { switch (keyCode) { // Find next case KeyEvent.KEYCODE_F3: if (searchItem.isActionViewExpanded()) queryTextListener.onQueryTextSubmit (searchView.getQuery().toString()); break; // Menu case KeyEvent.KEYCODE_F10: openOptionsMenu(); break; default: return super.onKeyDown(keyCode, event); } return true; } } // editClicked private void editClicked(MenuItem item) { // Get scroll position int y = scrollView.getScrollY(); // Get height int height = scrollView.getHeight(); // Get width int width = scrollView.getWidth(); // Get offset int line = textView.getLayout() .getLineForVertical(y + height / 2); int offset = textView.getLayout() .getOffsetForHorizontal(line, width / 2); // Set cursor textView.setSelection(offset); // Set editable with or without suggestions if (suggest) textView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE); else textView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); // Update boolean edit = true; // Recreate recreate(this); } // viewClicked private void viewClicked(MenuItem item) { // Set read only textView.setRawInputType(InputType.TYPE_NULL); textView.setTextIsSelectable(true); textView.clearFocus(); // Update boolean edit = false; // Update menu invalidateOptionsMenu(); } // newFile private void newFile() { // Check if file changed if (changed) alertDialog(this, R.string.newFile, R.string.modified, R.string.save, R.string.discard, (dialog, id) -> { switch (id) { case DialogInterface.BUTTON_POSITIVE: saveFile(); newFile(null); break; case DialogInterface.BUTTON_NEGATIVE: newFile(null); break; } invalidateOptionsMenu(); }); else newFile(null); invalidateOptionsMenu(); } // newFile private void newFile(String text) { textView.setText(""); changed = false; file = getNewFile(); uri = Uri.fromFile(file); path = uri.getPath(); content = null; if (text != null) textView.append(text); setTitle(uri.getLastPathSegment()); match = UTF_8; getActionBar().setSubtitle(match); } // getNewFile private static File getNewFile() { File documents = new File(Environment.getExternalStorageDirectory(), DOCUMENTS); return new File(documents, NEW_FILE); } // getDefaultFile private static File getDefaultFile() { File documents = new File(Environment.getExternalStorageDirectory(), DOCUMENTS); return new File(documents, EDIT_FILE); } // defaultFile private void defaultFile() { file = getDefaultFile(); uri = Uri.fromFile(file); path = uri.getPath(); content = null; if (file.exists()) readFile(uri); else { setTitle(uri.getLastPathSegment()); match = UTF_8; getActionBar().setSubtitle(match); } } // lastFile private void lastFile() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String path = preferences.getString(PREF_FILE, ""); if (path.isEmpty()) { defaultFile(); return; } file = new File(path); uri = Uri.fromFile(file); path = uri.getPath(); if (file.exists()) readFile(uri); else { setTitle(uri.getLastPathSegment()); match = UTF_8; getActionBar().setSubtitle(match); } } // setCharset private void setCharset(MenuItem item) { match = item.getTitle().toString(); getActionBar().setSubtitle(match); } // setTypeface private void setTypeface(MenuItem item) { String name = item.getTitle().toString(); Typeface typeface = Typeface.create(name, Typeface.NORMAL); textView.setTypeface(typeface); item.setChecked(true); String typefaces[] = getResources().getStringArray(R.array.typefaces); List list = Arrays.asList(typefaces); type = list.indexOf(name); } // alertDialog private static void alertDialog(Context context, int title, int message, int positiveButton, int negativeButton, DialogInterface.OnClickListener listener) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(title); builder.setMessage(message); // Add the buttons builder.setPositiveButton(positiveButton, listener); builder.setNegativeButton(negativeButton, listener); // Create the AlertDialog builder.show(); } // alertDialog private static void alertDialog(Context context, int title, String message, int neutralButton) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(title); builder.setMessage(message); // Add the buttons builder.setNeutralButton(neutralButton, null); // Create the AlertDialog builder.show(); } // savePath private void savePath(String path) { if (path == null) return; // Save the current position pathMap.put(path, scrollView.getScrollY()); // Get a list of files List list = new ArrayList<>(); Map map = new HashMap<>(); for (String name: pathMap.keySet()) { File file = new File(name); // Add to remove list if non existant if (!file.exists()) { removeList.add(name); continue; } list.add(file.lastModified()); map.put(file.lastModified(), name); } // Remove non existant entries for (String name: removeList) pathMap.remove(name); // Sort in reverse order Collections.sort(list); Collections.reverse(list); int count = 0; for (long date : list) { String name = map.get(date); // Remove old files if (count >= MAX_PATHS) { pathMap.remove(name); removeList.add(name); } count++; } } // openRecent private void openRecent(MenuItem item) { // Get path from condensed title String name = item.getTitleCondensed().toString(); File file = new File(name); // Check absolute file if (!file.isAbsolute()) file = new File(Environment.getExternalStorageDirectory(), name); // Check it exists if (file.exists()) { Uri uri = Uri.fromFile(file); if (changed) alertDialog(this, R.string.openRecent, R.string.modified, R.string.save, R.string.discard, (dialog, id) -> { switch (id) { case DialogInterface.BUTTON_POSITIVE: saveFile(); startActivity(new Intent(Intent.ACTION_EDIT, uri, this, Editor.class)); break; case DialogInterface.BUTTON_NEGATIVE: startActivity(new Intent(Intent.ACTION_EDIT, uri, this, Editor.class)); break; } }); else // New instance startActivity(new Intent(Intent.ACTION_EDIT, uri, this, Editor.class)); } } // saveAs private void saveAs() { // Remove path prefix String name = path.replaceFirst(Environment .getExternalStorageDirectory() .getPath() + File.separator, ""); // Open dialog saveAsDialog(this, name, (dialog, id) -> { switch (id) { case DialogInterface.BUTTON_POSITIVE: EditText text = ((Dialog) dialog).findViewById(R.id.pathText); String string = text.getText().toString(); // Ignore empty string if (string.isEmpty()) return; file = new File(string); // Check absolute file if (!file.isAbsolute()) file = new File(Environment.getExternalStorageDirectory(), string); // Check uri uri = Uri.fromFile(file); Uri newUri = Uri.fromFile(getNewFile()); if (newUri.getPath().equals(uri.getPath())) { saveAs(); return; } // Check exists if (file.exists()) alertDialog(this, R.string.appName, R.string.changedOverwrite, R.string.overwrite, R.string.cancel, (d, b) -> { switch (b) { case DialogInterface.BUTTON_POSITIVE: // Set interface title setTitle(uri.getLastPathSegment()); path = file.getPath(); saveFile(); break; } }); else { // Set interface title setTitle(uri.getLastPathSegment()); path = file.getPath(); content = null; saveFile(); } break; case DialogInterface.BUTTON_NEUTRAL: Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT); intent.setType(TEXT_WILD); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.putExtra(Intent.EXTRA_TITLE, uri.getLastPathSegment()); startActivityForResult(intent, CREATE_DOCUMENT); break; } }); } // saveAsDialog private static void saveAsDialog(Context context, String path, DialogInterface.OnClickListener listener) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.save); builder.setMessage(R.string.choose); // Add the buttons builder.setPositiveButton(R.string.save, listener); builder.setNegativeButton(R.string.cancel, listener); builder.setNeutralButton(R.string.storage, listener); // Create edit text LayoutInflater inflater = (LayoutInflater) builder.getContext() .getSystemService(LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.save_path, null); builder.setView(view); // Create the AlertDialog AlertDialog dialog = builder.show(); TextView text = dialog.findViewById(R.id.pathText); text.setText(path); } // clearList private void clearList() { for (String path : pathMap.keySet()) removeList.add(path); pathMap.clear(); } // findAll public void findAll() { // Get search string String search = searchView.getQuery().toString(); doFind(this, search); } // goTo public void goTo() { gotoDialog((seekBar, progress) -> { int height = textView.getHeight(); int pos = progress * height / seekBar.getMax(); // Scroll to it scrollView.smoothScrollTo(0, pos); }); } // OnSeekBarChangeListener public interface OnSeekBarChangeListener { abstract void onProgressChanged(SeekBar seekBar, int progress); } // GotoDialog private void gotoDialog(OnSeekBarChangeListener listener) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.goTo); // Add the buttons builder.setNegativeButton(R.string.cancel, null); // Create seek bar LayoutInflater inflater = (LayoutInflater) builder.getContext() .getSystemService(LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.seek_bar, null); builder.setView(view); // Create the AlertDialog AlertDialog dialog = builder.show(); SeekBar seekBar = dialog.findViewById(R.id.seekBar); int height = textView.getHeight(); int progress = scrollView.getScrollY() * seekBar.getMax() / height; seekBar.setProgress(progress); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) listener.onProgressChanged(seekBar, progress); } @Override public void onStartTrackingTouch (SeekBar seekBar) {} @Override public void onStopTrackingTouch (SeekBar seekBar) { dialog.dismiss(); } }); } // print @SuppressWarnings("deprecation") private void print() { WebView webView = new WebView(this); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; } @Override public void onPageFinished(WebView view, String url) { // Get a PrintManager instance PrintManager printManager = (PrintManager) getSystemService(PRINT_SERVICE); String jobName = getString(R.string.appName) + " Document"; // Get a print adapter instance PrintDocumentAdapter printAdapter = view.createPrintDocumentAdapter(jobName); // Create a print job with name and adapter instance printManager .print(jobName, printAdapter, new PrintAttributes.Builder() .setMediaSize(PrintAttributes.MediaSize.ISO_A4) .build()); } }); String htmlDocument = HTML_HEAD + Html.toHtml(textView.getText()) + HTML_TAIL; webView.loadData(htmlDocument, TEXT_HTML, UTF_8); } // viewMarkdown private void viewMarkdown() { String text = textView.getText().toString(); // Use commonmark Parser parser = Parser.builder().build(); Node document = parser.parse(text); HtmlRenderer renderer = HtmlRenderer.builder().build(); String html = renderer.render(document); File file = new File(getCacheDir(), HTML_FILE); file.deleteOnExit(); try (FileWriter writer = new FileWriter(file)) { // Add HTML header and footer to make a valid page. writer.write(HTML_HEAD); writer.write(html); writer.write(HTML_TAIL); } catch (Exception e) { e.printStackTrace(); } try { // Get file provider uri Uri uri = FileProvider.getUriForFile (this, FILE_PROVIDER, file); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(uri, TEXT_HTML); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } // viewFileClicked private void viewFileClicked(MenuItem item) { view = !view; item.setChecked(view); } // openLastClicked private void openLastClicked(MenuItem item) { last = !last; item.setChecked(last); } // autoSaveClicked private void autoSaveClicked(MenuItem item) { save = !save; item.setChecked(save); } // wrapClicked private void wrapClicked(MenuItem item) { wrap = !wrap; item.setChecked(wrap); recreate(this); } // suggestClicked private void suggestClicked(MenuItem item) { suggest = !suggest; item.setChecked(suggest); if (suggest) textView.setRawInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE); else textView.setRawInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); recreate(this); } // highlightClicked private void highlightClicked(MenuItem item) { highlight = !highlight; item.setChecked(highlight); checkHighlight(); } // lightClicked private void lightClicked(MenuItem item) { theme = LIGHT; item.setChecked(true); recreate(this); } // darkClicked private void darkClicked(MenuItem item) { theme = DARK; item.setChecked(true); recreate(this); } // systemClicked private void systemClicked(MenuItem item) { theme = SYSTEM; item.setChecked(true); recreate(this); } // whiteClicked private void whiteClicked(MenuItem item) { theme = WHITE; item.setChecked(true); recreate(this); } // blackClicked private void blackClicked(MenuItem item) { theme = BLACK; item.setChecked(true); recreate(this); } // retroClicked private void retroClicked(MenuItem item) { theme = RETRO; item.setChecked(true); recreate(this); } // smallClicked private void smallClicked(MenuItem item) { size = SMALL; item.setChecked(true); textView.setTextSize(size); } // mediumClicked private void mediumClicked(MenuItem item) { size = MEDIUM; item.setChecked(true); textView.setTextSize(size); } // largeClicked private void largeClicked(MenuItem item) { size = LARGE; item.setChecked(true); textView.setTextSize(size); } // setSizeAndTypeface private void setSizeAndTypeface(int size, int type) { // Set size textView.setTextSize(size); // Set type String names[] = getResources().getStringArray(R.array.typefaces); Typeface typeface = Typeface.create(names[type], Typeface.NORMAL); textView.setTypeface(typeface); } // aboutClicked @SuppressWarnings("deprecation") private void aboutClicked() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.appName); DateFormat dateFormat = DateFormat.getDateTimeInstance(); SpannableStringBuilder spannable = new SpannableStringBuilder(getText(R.string.version)); Pattern pattern = Pattern.compile("%s"); Matcher matcher = pattern.matcher(spannable); if (matcher.find()) spannable.replace(matcher.start(), matcher.end(), BuildConfig.VERSION_NAME); matcher.reset(spannable); if (matcher.find()) spannable.replace(matcher.start(), matcher.end(), dateFormat.format(BuildConfig.BUILT)); builder.setMessage(spannable); // Add the button builder.setPositiveButton(R.string.ok, null); // Create the AlertDialog Dialog dialog = builder.show(); // Set movement method TextView text = dialog.findViewById(android.R.id.message); if (text != null) { text.setTextAppearance(builder.getContext(), android.R.style.TextAppearance_Small); text.setMovementMethod(LinkMovementMethod.getInstance()); } } // recreate private void recreate(Context context) { if (Build.VERSION.SDK_INT != Build.VERSION_CODES.M) recreate(); } // openFile private void openFile() { // Check if file changed if (changed) alertDialog(this, R.string.open, R.string.modified, R.string.save, R.string.discard, (dialog, id) -> { switch (id) { case DialogInterface.BUTTON_POSITIVE: saveFile(); getFile(); break; case DialogInterface.BUTTON_NEGATIVE: changed = false; getFile(); break; } }); else getFile(); } // getFile private void getFile() { // Open parent folder File dir = file.getParentFile(); getFile(dir); } // getFile private void getFile(File dir) { // Get list of files List fileList = getList(dir); if (fileList == null) return; // Get list of folders List dirList = new ArrayList(); dirList.add(File.separator); dirList.addAll(Uri.fromFile(dir).getPathSegments()); // Pop up dialog openDialog(this, dirList, fileList, (dialog, which) -> { if (DialogInterface.BUTTON_NEUTRAL == which) { // Use storage Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.setType(TEXT_WILD); intent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(intent, OPEN_DOCUMENT); return; } if (FOLDER_OFFSET <= which) { File file = new File(File.separator); for (int i = 0; i <= which - FOLDER_OFFSET; i++) file = new File(file, dirList.get(i)); if (file.isDirectory()) getFile(file); return; } File selection = fileList.get(which); if (selection.isDirectory()) getFile(selection); else readFile(Uri.fromFile(selection)); }); } // getList public static List getList(File dir) { List list = null; File[] files = dir.listFiles(); // Check files if (files == null) { // Create a list with just the parent folder and the // external storage folder list = new ArrayList(); if (dir.getParentFile() == null) list.add(dir); else list.add(dir.getParentFile()); list.add(Environment.getExternalStorageDirectory()); return list; } // Sort the files Arrays.sort(files); // Create a list list = new ArrayList(Arrays.asList(files)); // Add parent folder if (dir.getParentFile() == null) list.add(0, dir); else list.add(0, dir.getParentFile()); return list; } // openDialog public static void openDialog(Context context, List dirList, List fileList, DialogInterface.OnClickListener listener) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(FOLDER); // Add the adapter FileAdapter adapter = new FileAdapter(builder.getContext(), fileList); builder.setAdapter(adapter, listener); // Add storage button builder.setNeutralButton(R.string.storage, listener); // Add cancel button builder.setNegativeButton(R.string.cancel, null); // Create the Dialog AlertDialog dialog = builder.create(); dialog.show(); // Find the title view ViewGroup title = dialog.findViewById (context.getResources().getIdentifier("title_template", "id", "android")); // Replace content with scroll view title.removeAllViews(); HorizontalScrollView scroll = new HorizontalScrollView(dialog.getContext()); title.addView(scroll); // Add a row of folder buttons LinearLayout layout = new LinearLayout(dialog.getContext()); scroll.addView(layout); for (String dir: dirList) { Button button = new Button(dialog.getContext(), null, android.R.attr.buttonStyleSmall); button.setId(dirList.indexOf(dir) + FOLDER_OFFSET); button.setText(dir); button.setOnClickListener((v) -> { listener.onClick(dialog, v.getId()); dialog.dismiss(); }); layout.addView(button); } // Scroll to the end scroll.postDelayed(() -> { scroll.fullScroll(View.FOCUS_RIGHT); }, POSITION_DELAY); } // onRequestPermissionsResult @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case REQUEST_OPEN: for (int i = 0; i < grantResults.length; i++) if (permissions[i].equals(Manifest.permission .READ_EXTERNAL_STORAGE) && grantResults[i] == PackageManager.PERMISSION_GRANTED) // Granted, open file getFile(); break; } } // readFile private void readFile(Uri uri) { if (uri == null) return; long size = 0; if (CONTENT.equalsIgnoreCase(uri.getScheme())) size = FileUtils.getSize(this, uri, null, null); else { File file = new File(uri.getPath()); size = file.length(); } if (BuildConfig.DEBUG) Log.d(TAG, "Size " + size); if (size > TOO_LARGE) { String large = getString(R.string.tooLarge); large = String.format(large, FileUtils.getReadableFileSize(size)); alertDialog(this, R.string.appName, large, R.string.ok); return; } // Stop highlighting textView.removeCallbacks(updateHighlight); textView.removeCallbacks(updateWordCount); if (BuildConfig.DEBUG) Log.d(TAG, "Uri: " + uri); // Attempt to resolve content uri if (CONTENT.equalsIgnoreCase(uri.getScheme())) { content = uri; uri = resolveContent(uri); } else content = null; if (BuildConfig.DEBUG) Log.d(TAG, "Uri: " + uri); // Read into new file if unresolved if (CONTENT.equalsIgnoreCase(uri.getScheme())) { file = getNewFile(); Uri defaultUri = Uri.fromFile(file); path = defaultUri.getPath(); setTitle(FileUtils.getDisplayName(this, content, null, null)); } // Read file else { this.uri = uri; path = uri.getPath(); file = new File(path); setTitle(uri.getLastPathSegment()); } textView.setText(R.string.loading); doRead(this, uri); changed = false; modified = file.lastModified(); savePath(path); invalidateOptionsMenu(); } // resolveContent private Uri resolveContent(Uri uri) { String path = FileUtils.getPath(this, uri); if (path != null) { File file = new File(path); if (file.canRead()) uri = Uri.fromFile(file); } return uri; } // saveCheck private void saveCheck() { Uri uri = Uri.fromFile(file); Uri newUri = Uri.fromFile(getNewFile()); if (content == null && newUri.getPath().equals(uri.getPath())) saveAs(); else saveFile(); } // saveFile private void saveFile() { // Stop highlighting textView.removeCallbacks(updateHighlight); textView.removeCallbacks(updateWordCount); if (file.lastModified() > modified) alertDialog(this, R.string.appName, R.string.changedOverwrite, R.string.overwrite, R.string.cancel, (dialog, id) -> { switch (id) { case DialogInterface.BUTTON_POSITIVE: saveFile(file); break; } }); else { if (content == null) saveFile(file); else saveFile(content); } } // saveFile private void saveFile(File file) { CharSequence text = textView.getText(); write(text, file); } // saveFile private void saveFile(Uri uri) { CharSequence text = textView.getText(); try (OutputStream outputStream = getContentResolver().openOutputStream(uri, "rwt")) { write(text, outputStream); } catch (Exception e) { alertDialog(this, R.string.appName, e.getMessage(), R.string.ok); e.printStackTrace(); return; } } // write private void write(CharSequence text, File file) { file.getParentFile().mkdirs(); String charset = UTF_8; if (match != null && !match.equals(getString(R.string.detect))) charset = match; try (BufferedWriter writer = new BufferedWriter (new OutputStreamWriter(new FileOutputStream(file), charset))) { writer.append(text); writer.flush(); } catch (Exception e) { alertDialog(this, R.string.appName, e.getMessage(), R.string.ok); e.printStackTrace(); return; } changed = false; invalidateOptionsMenu(); modified = file.lastModified(); savePath(file.getPath()); } // write private void write(CharSequence text, OutputStream os) { String charset = UTF_8; if (match != null && !match.equals(getString(R.string.detect))) charset = match; try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, charset))) { writer.append(text); writer.flush(); } catch (Exception e) { alertDialog(this, R.string.appName, e.getMessage(), R.string.ok); e.printStackTrace(); return; } changed = false; invalidateOptionsMenu(); } // checkHighlight private void checkHighlight() { // No syntax syntax = NO_SYNTAX; // Check extension if (highlight && file != null) { String ext = FileUtils.getExtension(file.getName()); if (ext != null) { String type = FileUtils.getMimeType(file); if (ext.matches(CC_EXT)) syntax = CC_SYNTAX; else if (ext.matches(HTML_EXT)) syntax = HTML_SYNTAX; else if (ext.matches(CSS_EXT)) syntax = CSS_SYNTAX; else if (ext.matches(ORG_EXT)) syntax = ORG_SYNTAX; else if (ext.matches(MD_EXT)) syntax = MD_SYNTAX; else if (ext.matches(SH_EXT)) syntax = SH_SYNTAX; else if (!TEXT_PLAIN.equals(type)) syntax = DEF_SYNTAX; else syntax = NO_SYNTAX; // Add callback if (textView != null && syntax != NO_SYNTAX) { if (updateHighlight == null) updateHighlight = () -> highlightText(); textView.removeCallbacks(updateHighlight); textView.postDelayed(updateHighlight, UPDATE_DELAY); return; } } } // Remove highlighting if (updateHighlight != null) { textView.removeCallbacks(updateHighlight); textView.postDelayed(updateHighlight, UPDATE_DELAY); updateHighlight = null; } } // highlightText private void highlightText() { // Get visible extent int top = scrollView.getScrollY(); int height = scrollView.getHeight(); int line = textView.getLayout().getLineForVertical(top); int start = textView.getLayout().getLineStart(line); int first = textView.getLayout().getLineStart(line + 1); line = textView.getLayout().getLineForVertical(top + height); int end = textView.getLayout().getLineEnd(line); int last = (line == 0)? end: textView.getLayout().getLineStart(line - 1); // Move selection if outside range if (textView.getSelectionStart() < start) textView.setSelection(first); if (textView.getSelectionStart() > end) textView.setSelection(last); // Get editable Editable editable = textView.getEditableText(); // Get current spans ForegroundColorSpan spans[] = editable.getSpans(start, end, ForegroundColorSpan.class); // Remove spans for (ForegroundColorSpan span: spans) editable.removeSpan(span); Matcher matcher; switch (syntax) { case NO_SYNTAX: // Get current spans spans = editable.getSpans(0, editable.length(), ForegroundColorSpan.class); // Remove spans for (ForegroundColorSpan span: spans) editable.removeSpan(span); break; case CC_SYNTAX: matcher = KEYWORDS.matcher(editable); matcher.region(start, end); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.CYAN); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(TYPES); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.MAGENTA); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(CLASS); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(NUMBER); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.YELLOW); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(ANNOTATION); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.CYAN); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(CONSTANT); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.LTGRAY); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(OPERATOR); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.CYAN); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(CC_COMMENT); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.RED); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } break; case HTML_SYNTAX: matcher = HTML_TAGS.matcher(editable); matcher.region(start, end); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.CYAN); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(HTML_ATTRS); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.MAGENTA); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(QUOTED); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.RED); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(HTML_COMMENT); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.RED); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } break; case CSS_SYNTAX: matcher = CSS_STYLES.matcher(editable); matcher.region(start, end); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.CYAN); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(CSS_HEX); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.MAGENTA); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(CC_COMMENT); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.RED); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } break; case ORG_SYNTAX: matcher = ORG_HEADER.matcher(editable); matcher.region(start, end); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(ORG_EMPH); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.MAGENTA); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(ORG_LINK); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.CYAN); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(ORG_COMMENT); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.RED); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } break; case MD_SYNTAX: matcher = MD_HEADER.matcher(editable); matcher.region(start, end); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(MD_LINK); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.CYAN); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(MD_EMPH); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.MAGENTA); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(MD_CODE); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.CYAN); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } break; case SH_SYNTAX: matcher = KEYWORDS.matcher(editable); matcher.region(start, end); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.CYAN); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(NUMBER); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.YELLOW); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(CONSTANT); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.LTGRAY); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(SH_VAR); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.MAGENTA); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(OPERATOR); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.CYAN); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(QUOTED); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.RED); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(SH_COMMENT); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.RED); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } break; case DEF_SYNTAX: matcher = KEYWORDS.matcher(editable); matcher.region(start, end); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.CYAN); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(TYPES); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.MAGENTA); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(CLASS); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(NUMBER); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.YELLOW); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(CONSTANT); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.LTGRAY); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } matcher.region(start, end).usePattern(QUOTED); while (matcher.find()) { ForegroundColorSpan span = new ForegroundColorSpan(Color.RED); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } break; } } // wordCountText private void wordCountText() { int words = 0; Matcher matcher = WORD_PATTERN.matcher(textView.getText()); while (matcher.find()) { words++; } if (customView != null) { String string = String.format(Locale.getDefault(), "%d\n%d", words, textView.length()); customView.setText(string); } } // onActionModeStarted @Override public void onActionModeStarted(ActionMode mode) { super.onActionModeStarted(mode); // If there's a file if (file != null) { // Get the mime type String type = FileUtils.getMimeType(file); // If the type is not text/plain if (!TEXT_PLAIN.equals(type)) { // Get the start and end of the selection int start = textView.getSelectionStart(); int end = textView.getSelectionEnd(); // And the text CharSequence text = textView.getText(); // Get a pattern and a matcher for delimiter // characters Matcher matcher = PATTERN_CHARS.matcher(text); // Find the first match after the end of the selection if (matcher.find(end)) { // Update the selection end end = matcher.start(); // Get the matched char char c = text.charAt(end); // Check for opening brackets if (BRACKET_CHARS.indexOf(c) == -1) { switch (c) { // Check for close brackets and look for // the open brackets case ')': c = '('; break; case ']': c = '['; break; case '}': c = '{'; break; case '>': c = '<'; break; } String string = text.toString(); // Do reverse search start = string.lastIndexOf(c, start) + 1; // Check for included newline if (start > string.lastIndexOf('\n', end)) // Update selection textView.setSelection(start, end); } } } } } // checkMode private void checkMode(CharSequence text) { boolean change = false; CharSequence first = text.subSequence (0, Math.min(text.length(), FIRST_SIZE)); CharSequence last = text.subSequence (Math.max(0, text.length() - LAST_SIZE), text.length()); for (CharSequence sequence: new CharSequence[]{first, last}) { Matcher matcher = MODE_PATTERN.matcher(sequence); if (matcher.find()) { matcher.region(matcher.start(1), matcher.end(1)); matcher.usePattern(OPTION_PATTERN); while (matcher.find()) { boolean no = "no".equals(matcher.group(2)); if ("vw".equals(matcher.group(3))) { if (view == no) { view = !no; change = true; } } else if ("ww".equals(matcher.group(3))) { if (wrap == no) { wrap = !no; change = true; } } else if ("sg".equals(matcher.group(3))) { if (suggest == no) { suggest = !no; change = true; } } else if ("hs".equals(matcher.group(3))) { if (highlight == no) { highlight = !no; checkHighlight(); } } else if ("th".equals(matcher.group(3))) { if (":l".equals(matcher.group(4))) { if (theme != LIGHT) { theme = LIGHT; change = true; } } else if (":d".equals(matcher.group(4))) { if (theme != DARK) { theme = DARK; change = true; } } else if (":s".equals(matcher.group(4))) { if (theme != SYSTEM) { theme = SYSTEM; change = true; } } else if (":w".equals(matcher.group(4))) { if (theme != WHITE) { theme = WHITE; change = true; } } else if (":b".equals(matcher.group(4))) { if (theme != BLACK) { theme = BLACK; change = true; } } else if (":r".equals(matcher.group(4))) { if (theme != RETRO) { theme = RETRO; change = true; } } } else if ("ts".equals(matcher.group(3))) { if (":l".equals(matcher.group(4))) { if (size != LARGE) { size = LARGE; textView.setTextSize(size); } } else if (":m".equals(matcher.group(4))) { if (size != MEDIUM) { size = MEDIUM; textView.setTextSize(size); } } else if (":s".equals(matcher.group(4))) { if (size != SMALL) { size = SMALL; textView.setTextSize(size); } } } else if ("tf".equals(matcher.group(3))) { if (":m".equals(matcher.group(4))) { if (type != MONO) { type = MONO; textView.setTypeface(Typeface.MONOSPACE); } } else if (":p".equals(matcher.group(4))) { if (type != NORMAL) { type = NORMAL; textView.setTypeface(Typeface.DEFAULT); } } else if (":s".equals(matcher.group(4))) { if (type != SERIF) { type = SERIF; textView.setTypeface(Typeface.SERIF); } } } else if ("cs".equals(matcher.group(3))) { if (":u".equals(matcher.group(4))) { match = UTF_8; getActionBar().setSubtitle(match); } } } } } if (change) recreate(this); } // loadText private void loadText(CharSequence text) { if (textView != null) textView.setText(text); changed = false; // Check for saved position if (pathMap.containsKey(path)) textView.postDelayed(() -> scrollView.smoothScrollTo (0, pathMap.get(path)), POSITION_DELAY); else textView.postDelayed(() -> scrollView.smoothScrollTo(0, 0), POSITION_DELAY); // Check mode checkMode(text); // Check highlighting checkHighlight(); // Set read only if (view) { textView.setRawInputType(InputType.TYPE_NULL); textView.setTextIsSelectable(true); // Update boolean edit = false; } else { // Set editable with or without suggestions if (suggest) textView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE); else textView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); // Update boolean edit = true; } // Dismiss keyboard textView.clearFocus(); // Update menu invalidateOptionsMenu(); } // QueryTextListener private class QueryTextListener implements SearchView.OnQueryTextListener { private BackgroundColorSpan span = new BackgroundColorSpan(Color.YELLOW); private Editable editable; private Matcher matcher; private Pattern pattern; private int index; private int height; // onQueryTextChange @Override @SuppressWarnings("deprecation") public boolean onQueryTextChange(String newText) { // Use regex search and spannable for highlighting height = scrollView.getHeight(); editable = textView.getEditableText(); // Reset the index and clear highlighting if (newText.length() == 0) { index = 0; editable.removeSpan(span); return false; } // Check pattern try { pattern = Pattern.compile(newText, Pattern.MULTILINE); matcher = pattern.matcher(editable); } catch (Exception e) { return false; } // Find text if (matcher.find(index)) { // Get index index = matcher.start(); // Check layout if (textView.getLayout() == null) return false; // Get text position int line = textView.getLayout().getLineForOffset(index); int pos = textView.getLayout().getLineBaseline(line); // Scroll to it scrollView.smoothScrollTo(0, pos - height / 2); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else index = 0; return true; } // onQueryTextSubmit @Override public boolean onQueryTextSubmit(String query) { // Check matcher if (matcher == null) return false; // Find next text if (matcher.find()) { // Get index index = matcher.start(); // Get text position int line = textView.getLayout().getLineForOffset(index); int pos = textView.getLayout().getLineBaseline(line); // Scroll to it scrollView.smoothScrollTo(0, pos - height / 2); // Highlight it editable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else { matcher.reset(); index = 0; } return true; } } // readFile private CharSequence readFile(File file) { StringBuilder text = new StringBuilder(); // Open file try (BufferedReader reader = new BufferedReader (new InputStreamReader (new BufferedInputStream(new FileInputStream(file))))) { String line; while ((line = reader.readLine()) != null) { text.append(line); text.append(System.getProperty("line.separator")); } return text; } catch (Exception e) { e.printStackTrace(); } return text; } // ScaleListener private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { // onScale @Override public boolean onScale(ScaleGestureDetector detector) { size *= Math.cbrt(detector.getScaleFactor()); size = Math.max(TINY, Math.min(size, HUGE)); textView.setTextSize(size); invalidateOptionsMenu(); return true; } } private void doFind(Context context, String search) { List matchList = new ArrayList<>(); List entries = new ArrayList<>(); // Get entry list for (String path : pathMap.keySet()) { File entry = new File(path); entries.add(entry); } executor.execute(() -> { Pattern pattern = null; try { // Compile search pattern pattern = Pattern.compile(search, Pattern.MULTILINE); } catch (Exception e) {} // Check the entries for (File file : entries) { CharSequence content = readFile(file); Matcher matcher = pattern.matcher(content); if (matcher.find()) matchList.add(file); } runOnUiThread(() -> { // Build dialog AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.findAll); // If found populate dialog if (!matchList.isEmpty()) { List choiceList = new ArrayList<>(); for (File file : matchList) { // Remove path prefix String path = file.getPath(); String name = path.replaceFirst(Environment .getExternalStorageDirectory() .getPath() + File.separator, ""); choiceList.add(name); } String[] choices = choiceList.toArray(new String[0]); builder.setItems(choices, (dialog, which) -> { File file = matchList.get(which); Uri uri = Uri.fromFile(file); // Open the entry chosen readFile(uri); // Put the search text back - why it // disappears I have no idea or why I have to // do it after a delay searchView.postDelayed(() -> searchView.setQuery(search, false), FIND_DELAY); }); } builder.setNegativeButton(android.R.string.cancel, null); builder.show(); }); }); } // doRead private void doRead(Context context, Uri uri) { StringBuilder stringBuilder = new StringBuilder(); // Default UTF-8 if (match == null) { match = UTF_8; getActionBar().setSubtitle(match); } executor.execute(() -> { try (BufferedInputStream in = new BufferedInputStream (getContentResolver().openInputStream(uri))) { // Create reader BufferedReader reader = null; if (match.equals(getString(R.string.detect))) { // Detect charset, using UTF-8 hint CharsetMatch charsetMatch = new CharsetDetector().setDeclaredEncoding(UTF_8) .setText(in).detect(); if (charsetMatch != null) { match = charsetMatch.getName(); runOnUiThread(() -> getActionBar().setSubtitle(match)); reader = new BufferedReader(charsetMatch.getReader()); } else reader = new BufferedReader (new InputStreamReader(in)); if (BuildConfig.DEBUG && match != null) Log.d(TAG, "Charset " + match); } else reader = new BufferedReader (new InputStreamReader(in, match)); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append(System.getProperty("line.separator")); } } catch (Exception e) { runOnUiThread(() -> alertDialog(context, R.string.appName, e.getMessage(), R.string.ok)); e.printStackTrace(); } runOnUiThread(() -> loadText(stringBuilder)); }); } } ================================================ FILE: src/main/java/org/billthefarmer/editor/FileAdapter.java ================================================ //////////////////////////////////////////////////////////////////////////////// // // Editor - Text editor for Android // // Copyright © 2017 Bill Farmer // // 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 . // //////////////////////////////////////////////////////////////////////////////// package org.billthefarmer.editor; import android.content.Context; import android.content.res.TypedArray; import android.os.Environment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.io.File; import java.util.List; // FileAdapter class public class FileAdapter extends BaseAdapter { private final static String TAG = "FileAdapter"; private final static String ROOT = "/"; private final static String IMAGE_SVG = "image/svg"; private final static String IMAGE = "image"; private final static String AUDIO = "audio"; private final static String VIDEO = "video"; private final static String APPLICATION = "application"; private final static long TOO_LARGE = 524288; private LayoutInflater inflater; private List files; private int fileId; private int audioId; private int imageId; private int videoId; private int folderId; private int parentId; private int externalId; private int applicationId; // Constructor public FileAdapter(Context context, List files) { inflater = LayoutInflater.from(context); this.files = files; final TypedArray typedArray = context.obtainStyledAttributes(R.styleable.Editor); if (typedArray.hasValue(R.styleable.Editor_folder)) folderId = typedArray.getResourceId(R.styleable.Editor_folder, 0); if (typedArray.hasValue(R.styleable.Editor_parent)) parentId = typedArray.getResourceId(R.styleable.Editor_parent, 0); if (typedArray.hasValue(R.styleable.Editor_file)) fileId = typedArray.getResourceId(R.styleable.Editor_file, 0); if (typedArray.hasValue(R.styleable.Editor_audio)) audioId = typedArray.getResourceId(R.styleable.Editor_audio, 0); if (typedArray.hasValue(R.styleable.Editor_image)) imageId = typedArray.getResourceId(R.styleable.Editor_image, 0); if (typedArray.hasValue(R.styleable.Editor_video)) videoId = typedArray.getResourceId(R.styleable.Editor_video, 0); if (typedArray.hasValue(R.styleable.Editor_external)) externalId = typedArray.getResourceId(R.styleable.Editor_external, 0); if (typedArray.hasValue(R.styleable.Editor_application)) applicationId = typedArray.getResourceId(R.styleable.Editor_application, 0); typedArray.recycle(); } @Override public int getCount() { return files.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } // Create a new View for each item referenced by the adapter @Override public View getView(int position, View convertView, ViewGroup parent) { // Create a new view if (convertView == null) convertView = inflater.inflate(R.layout.file, parent, false); // Find the views TextView name = convertView.findViewById(R.id.name); File file = files.get(position); if (name != null) { if (file.getParentFile() == null) name.setText(ROOT); else name.setText(file.getName()); name.setEnabled(true); name.setClickable(false); if (file.isDirectory()) { if (position == 0) name.setCompoundDrawablesWithIntrinsicBounds(parentId, 0, 0, 0); else name.setCompoundDrawablesWithIntrinsicBounds(folderId, 0, 0, 0); } else { // Get the mime type String type = FileUtils.getMimeType(file); if (type != null && type.startsWith(IMAGE_SVG)) name.setCompoundDrawablesWithIntrinsicBounds(imageId, 0, 0, 0); else if (type != null && type.startsWith(IMAGE)) { name.setEnabled(false); name.setClickable(true); name.setCompoundDrawablesWithIntrinsicBounds(imageId, 0, 0, 0); } else if (type != null && type.startsWith(AUDIO)) { name.setEnabled(false); name.setClickable(true); name.setCompoundDrawablesWithIntrinsicBounds(audioId, 0, 0, 0); } else if (type != null && type.startsWith(VIDEO)) { name.setEnabled(false); name.setClickable(true); name.setCompoundDrawablesWithIntrinsicBounds(videoId, 0, 0, 0); } else if (type != null && type.startsWith(APPLICATION)) name.setCompoundDrawablesWithIntrinsicBounds(applicationId, 0, 0, 0); else name.setCompoundDrawablesWithIntrinsicBounds(fileId, 0, 0, 0); } // Too large if (file.length() > TOO_LARGE) { name.setEnabled(false); name.setClickable(true); } } return convertView; } } ================================================ FILE: src/main/java/org/billthefarmer/editor/FileUtils.java ================================================ /* * Copyright (C) 2018 OpenIntents.org * * 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 org.billthefarmer.editor; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.DatabaseUtils; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.provider.OpenableColumns; import android.util.Log; import android.webkit.MimeTypeMap; import java.io.File; import java.io.FileFilter; import java.text.DecimalFormat; import java.util.Comparator; import java.util.List; import java.util.Locale; /** * @author Peli * @author paulburke (ipaulpro) * @author Bill Farmer (billthefarmer) * @version 2017-06-22 */ public class FileUtils { /** * TAG for log messages. */ private static final String TAG = "FileUtils"; // pattern /** * File and folder comparator. TODO Expose sorting option method * * @author paulburke */ public static Comparator sComparator = (f1, f2) -> { // Sort alphabetically by lower case, which is much cleaner return f1.getName().toLowerCase(Locale.getDefault()) .compareTo(f2.getName().toLowerCase(Locale.getDefault())); }; public static final String MIME_TYPE_AUDIO = "audio/*"; public static final String MIME_TYPE_TEXT = "text/*"; public static final String MIME_TYPE_IMAGE = "image/*"; public static final String MIME_TYPE_VIDEO = "video/*"; public static final String MIME_TYPE_APP = "application/*"; public static final String HIDDEN_PREFIX = "."; /** * File (not directories) filter. * * @author paulburke */ public static FileFilter sFileFilter = file -> { final String fileName = file.getName(); // Return files only (not directories) and skip hidden files return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX); }; /** * Folder (directories) filter. * * @author paulburke */ public static FileFilter sDirFilter = file -> { final String fileName = file.getName(); // Return directories only and skip hidden directories return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX); }; private FileUtils() { } // private constructor to enforce Singleton /** * Gets the extension of a file name, like ".png" or ".jpg". * * @param uri * @return Extension including the dot("."); "" if there is no * extension; null if uri was null. */ public static String getExtension(String uri) { if (uri == null) { return null; } int dot = uri.lastIndexOf("."); if (dot >= 0) { return uri.substring(dot); } else { // No extension. return ""; } } /** * @return Whether the URI is a local one. */ public static boolean isLocal(String url) { return url != null && !url.startsWith("http://") && !url.startsWith("https://"); } /** * @return True if Uri is a MediaStore Uri. * @author paulburke */ public static boolean isMediaUri(Uri uri) { return "media".equalsIgnoreCase(uri.getAuthority()); } /** * Convert File into Uri. * * @param file * @return uri */ public static Uri getUri(File file) { return (file != null) ? Uri.fromFile(file) : null; } /** * Returns the path only (without file name). * * @param file * @return */ public static File getPathWithoutFilename(File file) { if (file != null) { if (file.isDirectory()) { // no file to be split off. Return everything return file; } else { String filename = file.getName(); String filepath = file.getAbsolutePath(); // Construct path without file name. String pathwithoutname = filepath.substring(0, filepath.length() - filename.length()); if (pathwithoutname.endsWith(File.separator)) { pathwithoutname = pathwithoutname .substring(0, pathwithoutname.length() - 1); } return new File(pathwithoutname); } } return null; } /** * @return The MIME type for the given file. */ public static String getMimeType(File file) { String extension = getExtension(file.getName()).toLowerCase(Locale.getDefault()); if (extension.length() > 0) return MimeTypeMap.getSingleton() .getMimeTypeFromExtension(extension.substring(1)); return "application/octet-stream"; } /** * @return The MIME type for the give Uri. */ public static String getMimeType(Context context, Uri uri) { File file = new File(getPath(context, uri)); return getMimeType(file); } /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. * @author paulburke */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents" .equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. * @author paulburke */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents" .equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. * @author paulburke */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents" .equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is Google Photos. */ public static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content" .equals(uri.getAuthority()); } /** * @param uri The Uri to match. * @return The file path from the FileProvider Uri. * @author billthefarmer */ public static String fileProviderPath(Uri uri) { List uriList = uri.getPathSegments(); if (BuildConfig.DEBUG) { Log.d(TAG, "Uri: " + uri); Log.d(TAG, "Path: " + uriList); } List segments = uriList.subList(1, uriList.size()); // Try root path if (uriList.size() > 3) { StringBuilder path = new StringBuilder(); for (String segment : segments) { path.append(File.separator); path.append(segment); } if (BuildConfig.DEBUG) Log.d(TAG, "Path: " + path); File file = new File(path.toString()); if (file.isFile()) return path.toString(); } // Try external storage path if (uriList.size() > 1) { StringBuilder path = new StringBuilder(); path.append(Environment.getExternalStorageDirectory()); for (String segment : segments) { path.append(File.separator); path.append(segment); } if (BuildConfig.DEBUG) Log.d(TAG, "Path: " + path); File file = new File(path.toString()); if (file.isFile()) return path.toString(); } return null; } /** * Get the display name for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the * query. * @return The display name of the file referred to by the Uri * @author Bill Farmer */ public static String getDisplayName(Context context, Uri uri, String selection, String[] selectionArgs) { final String column = OpenableColumns.DISPLAY_NAME; final String[] projection = { column }; try (Cursor cursor = context.getContentResolver() .query(uri, projection, selection, selectionArgs, null)) { if (cursor != null && cursor.moveToFirst()) { if (BuildConfig.DEBUG) DatabaseUtils.dumpCursor(cursor); final int column_index = cursor.getColumnIndex(column); if (column_index >= 0) return cursor.getString(column_index); } } catch (Exception e) {} return null; } /** * Get the size for this Uri. This is useful for MediaStore Uris, * and other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the * query. * @return The size of the file referred to by the Uri * @author Bill Farmer */ public static long getSize(Context context, Uri uri, String selection, String[] selectionArgs) { final String column = OpenableColumns.SIZE; final String[] projection = { column }; try (Cursor cursor = context.getContentResolver() .query(uri, projection, selection, selectionArgs, null)) { if (cursor != null && cursor.moveToFirst()) { if (BuildConfig.DEBUG) DatabaseUtils.dumpCursor(cursor); final int column_index = cursor.getColumnIndex(column); if (column_index >= 0) return cursor.getLong(column_index); } } catch (Exception e) {} return 0; } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the * query. * @return The value of the _data column, which is typically a * file path. * @author paulburke */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { final String column = MediaStore.MediaColumns.DATA; final String[] projection = { column }; try (Cursor cursor = context.getContentResolver() .query(uri, projection, selection, selectionArgs, null)) { if (cursor != null && cursor.moveToFirst()) { if (BuildConfig.DEBUG) DatabaseUtils.dumpCursor(cursor); final int column_index = cursor.getColumnIndex(column); if (column_index >= 0) return cursor.getString(column_index); } } catch (Exception e) {} return null; } /** * Get a file path from a Uri. This will get the the path for * Storage Access Framework Documents, as well as the _data field * for the MediaStore and other file-based ContentProviders.
*
* Callers should check whether the path is local before assuming * it represents a local file. * * @param context The context. * @param uri The Uri to query. * @author paulburke * @see #isLocal(String) * @see #getFile(Context, Uri) */ public static String getPath(final Context context, final Uri uri) { if (BuildConfig.DEBUG) Log.d(TAG, "File: " + "Authority: " + uri.getAuthority() + ", Fragment: " + uri.getFragment() + ", Port: " + uri.getPort() + ", Query: " + uri.getQuery() + ", Scheme: " + uri.getScheme() + ", Host: " + uri.getHost() + ", Segments: " + uri.getPathSegments().toString() ); // DocumentProvider if (DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final List segments = uri.getPathSegments(); final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; final String id = split[1]; if (BuildConfig.DEBUG) Log.d(TAG, "Segments: " + segments); if (BuildConfig.DEBUG) Log.d(TAG, "DocId: " + docId); if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + File.separator + id; } else if ("home".equalsIgnoreCase(type)) { return Environment .getExternalStorageDirectory() + "/Documents/" + id; } else if (type != null && type.matches("[0-9A-Z]{4}-[0-9A-Z]{4}")) { List storage = Uri.fromFile(Environment.getExternalStorageDirectory()) .getPathSegments(); return File.separator + storage.get(0) + File.separator + type + File.separator + id; } else if ("document".equalsIgnoreCase(segments.get(0))) { return Environment .getExternalStorageDirectory() + File.separator + id; } // TODO handle non-primary volumes } // DownloadsProvider else if (isDownloadsDocument(uri)) { // Check for non-numeric id try { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris .withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // Id not a number catch (Exception e) { return getDataColumn(context, uri, null, null); } } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; final String id = split[1]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { id }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { // Return the remote address if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); // Return ContentProvider path String path = getDataColumn(context, uri, null, null); if (path != null) return path; // Return FileProvider path return fileProviderPath(uri); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } /** * Convert Uri into File, if possible. * * @return file A local file that the Uri was pointing to, or null * if the Uri is unsupported or pointed to a remote * resource. * @author paulburke * @see #getPath(Context, Uri) */ public static File getFile(Context context, Uri uri) { if (uri != null) { String path = getPath(context, uri); if (isLocal(path)) { return new File(path); } } return null; } /** * Get the file size in a human-readable string. * * @param size * @return * @author paulburke */ public static String getReadableFileSize(long size) { final int BYTES_IN_KILOBYTES = 1024; final DecimalFormat dec = new DecimalFormat("###.#"); final String KILOBYTES = " KB"; final String MEGABYTES = " MB"; final String GIGABYTES = " GB"; float fileSize = 0; String suffix = KILOBYTES; if (size > BYTES_IN_KILOBYTES) { fileSize = size / BYTES_IN_KILOBYTES; if (fileSize > BYTES_IN_KILOBYTES) { fileSize = fileSize / BYTES_IN_KILOBYTES; if (fileSize > BYTES_IN_KILOBYTES) { fileSize = fileSize / BYTES_IN_KILOBYTES; suffix = GIGABYTES; } else { suffix = MEGABYTES; } } } return String.valueOf(dec.format(fileSize) + suffix); } /** * Attempt to retrieve the thumbnail of given File from the * MediaStore. This should not be called on the UI thread. * * @param context * @param file * @return * @author paulburke */ public static Bitmap getThumbnail(Context context, File file) { return getThumbnail(context, getUri(file), getMimeType(file)); } /** * Attempt to retrieve the thumbnail of given Uri from the * MediaStore. This should not be called on the UI thread. * * @param context * @param uri * @return * @author paulburke */ public static Bitmap getThumbnail(Context context, Uri uri) { return getThumbnail(context, uri, getMimeType(context, uri)); } /** * Attempt to retrieve the thumbnail of given Uri from the * MediaStore. This should not be called on the UI thread. * * @param context * @param uri * @param mimeType * @return * @author paulburke */ @SuppressWarnings("deprecation") public static Bitmap getThumbnail(Context context, Uri uri, String mimeType) { if (BuildConfig.DEBUG) Log.d(TAG, "Attempting to get thumbnail"); if (!isMediaUri(uri)) { Log.e(TAG, "You can only retrieve thumbnails for images and videos."); return null; } Bitmap bm = null; final ContentResolver resolver = context.getContentResolver(); try (Cursor cursor = resolver.query(uri, null, null, null, null)) { if (cursor.moveToFirst()) { final int id = cursor.getInt(0); if (BuildConfig.DEBUG) Log.d(TAG, "Got thumb ID: " + id); if (mimeType.contains("video")) { bm = MediaStore.Video.Thumbnails.getThumbnail( resolver, id, MediaStore.Video.Thumbnails.MINI_KIND, null); } else if (mimeType.contains(FileUtils.MIME_TYPE_IMAGE)) { bm = MediaStore.Images.Thumbnails.getThumbnail( resolver, id, MediaStore.Images.Thumbnails.MINI_KIND, null); } } } catch (Exception e) { if (BuildConfig.DEBUG) Log.e(TAG, "getThumbnail", e); } return bm; } /** * Get the Intent for selecting content to be used in an Intent Chooser. * * @return The intent for opening a file with Intent.createChooser() * @author paulburke */ public static Intent createGetContentIntent() { // Implicitly allow the user to select a particular kind of data final Intent intent = new Intent(Intent.ACTION_GET_CONTENT); // The MIME data type filter intent.setType("*/*"); // Only return URIs that can be opened with ContentResolver intent.addCategory(Intent.CATEGORY_OPENABLE); return intent; } } ================================================ FILE: src/main/java/org/billthefarmer/editor/NewFile.java ================================================ //////////////////////////////////////////////////////////////////////////////// // // Editor - Text editor for Android // // Copyright © 2019 Bill Farmer // // 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 . // // Bill Farmer william j farmer [at] yahoo [dot] co [dot] uk. // //////////////////////////////////////////////////////////////////////////////// package org.billthefarmer.editor; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class NewFile extends Activity { public final static String TAG = "NewFile"; // onCreate @Override @SuppressWarnings("deprecation") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create the shortcut intent Intent shortcut = new Intent(this, Editor.class); shortcut.setAction(Editor.OPEN_NEW); shortcut.addCategory(Intent.CATEGORY_DEFAULT); // Create the shortcut Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcut); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.newFile)); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext (this, R.drawable.ic_launcher)); setResult(RESULT_OK, intent); finish(); } } ================================================ FILE: src/main/java/org/billthefarmer/editor/OpenFile.java ================================================ //////////////////////////////////////////////////////////////////////////////// // // Editor - Text editor for Android // // Copyright © 2019 Bill Farmer // // 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 . // // Bill Farmer william j farmer [at] yahoo [dot] co [dot] uk. // //////////////////////////////////////////////////////////////////////////////// package org.billthefarmer.editor; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; import android.widget.TextView; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class OpenFile extends Activity { public final static String TAG = "OpenFile"; private TextView nameView; private TextView pathView; private String path; private File file; private Uri uri; // onCreate @Override @SuppressWarnings("deprecation") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Get preferences SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); int theme = preferences.getInt(Editor.PREF_THEME, Editor.LIGHT); // Get day/night mode Configuration config = getResources().getConfiguration(); int night = config.uiMode & Configuration.UI_MODE_NIGHT_MASK; // Set theme switch (theme) { case Editor.LIGHT: setTheme(R.style.DialogTheme); break; case Editor.DARK: setTheme(R.style.DialogDarkTheme); break; case Editor.SYSTEM: switch (night) { case Configuration.UI_MODE_NIGHT_NO: setTheme(R.style.DialogTheme); break; case Configuration.UI_MODE_NIGHT_YES: setTheme(R.style.DialogDarkTheme); break; } break; case Editor.WHITE: setTheme(R.style.DialogWhiteTheme); break; case Editor.BLACK: setTheme(R.style.DialogBlackTheme); break; case Editor.RETRO: setTheme(R.style.DialogRetroTheme); break; } // Set content setContentView(R.layout.open_file); // Find views nameView = findViewById(R.id.name); pathView = findViewById(R.id.path); // Get last path boolean last = preferences.getBoolean(Editor.PREF_LAST, false); String lastPath = preferences.getString(Editor.PREF_FILE, ""); // Configure buttons Button cancel = findViewById(R.id.cancel); cancel.setOnClickListener((v) -> { setResult(RESULT_CANCELED, null); finish(); }); Button openFile = findViewById(R.id.openFile); openFile.setOnClickListener((v) -> { if (last && !lastPath.isEmpty()) getFile(new File(lastPath).getParentFile()); else getFile(new File(Environment.getExternalStorageDirectory(), Editor.DOCUMENTS)); }); Button create = findViewById(R.id.create); create.setOnClickListener((v) -> { if (pathView.length() == 0) return; // Create the shortcut intent Intent shortcut = new Intent(this, Editor.class); shortcut.setAction(Intent.ACTION_EDIT); shortcut.addCategory(Intent.CATEGORY_DEFAULT); if (uri == null) { file = new File(pathView.getText().toString()); if (!file.isAbsolute()) file = new File(Environment.getExternalStorageDirectory(), file.getPath()); uri = Uri.fromFile(file); if (nameView.length() == 0) nameView.setText(uri.getLastPathSegment()); } // Set uri shortcut.setData(uri); // Create the shortcut Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcut); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, nameView.getText().toString()); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext (this, R.drawable.ic_launcher)); setResult(RESULT_OK, intent); finish(); }); // Check permissions if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, Editor.REQUEST_OPEN); return; } } if (last && !lastPath.isEmpty()) getFile(new File(lastPath).getParentFile()); else getFile(new File(Environment.getExternalStorageDirectory(), Editor.DOCUMENTS)); } // onRequestPermissionsResult @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case Editor.REQUEST_OPEN: for (int i = 0; i < grantResults.length; i++) if (permissions[i].equals(Manifest.permission .READ_EXTERNAL_STORAGE) && grantResults[i] == PackageManager.PERMISSION_GRANTED) // Granted, get file getFile(new File(Environment.getExternalStorageDirectory(), Editor.DOCUMENTS)); break; } } // onActivityResult @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_CANCELED) return; switch (requestCode) { case Editor.OPEN_DOCUMENT: uri = data.getData(); path = uri.getPath(); pathView.setText(path); nameView.setText(FileUtils.getDisplayName(this, uri, null, null)); break; } } // getFile private void getFile(File dir) { // Get list of files List fileList = Editor.getList(dir); if (fileList == null) return; // Get list of folders List dirList = new ArrayList(); dirList.add(File.separator); dirList.addAll(Uri.fromFile(dir).getPathSegments()); // Pop up dialog Editor.openDialog(this, dirList, fileList, (dialog, which) -> { if (DialogInterface.BUTTON_NEUTRAL == which) { // Use storage Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.setType(Editor.TEXT_WILD); intent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(intent, Editor.OPEN_DOCUMENT); return; } if (Editor.FOLDER_OFFSET <= which) { File file = new File(File.separator); for (int i = 0; i <= which - Editor.FOLDER_OFFSET; i++) file = new File(file, dirList.get(i)); if (file.isDirectory()) getFile(file); return; } File selection = fileList.get(which); if (selection.isDirectory()) getFile(selection); else { uri = Uri.fromFile(selection); path = uri.getPath(); pathView.setText(path); nameView.setText(uri.getLastPathSegment()); } }); } } ================================================ FILE: src/main/res/color/text_color_retro.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_add_black_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_add_white_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_edit_black_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_edit_white_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_folder_open_black_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_folder_open_white_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_image_black_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_image_white_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_list_black_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_list_white_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_reply_black_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_reply_white_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_save_black_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_save_white_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_sd_storage_black_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_sd_storage_white_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_stop_black_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_stop_white_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_videocam_black_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_videocam_white_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_volume_up_black_24dp.xml ================================================ ================================================ FILE: src/main/res/drawable/ic_volume_up_white_24dp.xml ================================================ ================================================ FILE: src/main/res/layout/custom.xml ================================================ ================================================ FILE: src/main/res/layout/edit.xml ================================================ ================================================ FILE: src/main/res/layout/file.xml ================================================ ================================================ FILE: src/main/res/layout/open_file.xml ================================================