Recently Written · git

subread-dictionary

Pop-up dictionary for Android that reads Yomitan dictionaries, with local audio

git clone https://github.com/equwal/subread-dictionary

Log | Files | Refs


commit 366948cd2fd0a00f9ff8ef44f0d8b8c83ae0e134
equwal <truex@equwal.com>
2026-09-21 20:52:52 -0700

Add SubRead Dictionary

A pop-up dictionary for Yomitan dictionaries. The pop-up takes a text from
the text selection menu, the share sheet, or the LOOKUP intent of SubRead
Overlay. :core reads the dictionary zip, deinflects Japanese and renders the
glossary; :app stores the terms in SQLite and plays local (android.db) and
remote audio.

 .gitignore                                         |  20 +
 LICENSE                                            | 662 +++++++++++++++++++++
 README.md                                          |  70 +++
 app/build.gradle.kts                               |  70 +++
 .../space/subread/dictionary/DictionariesTest.kt   | 101 ++++
 app/src/main/AndroidManifest.xml                   |  54 ++
 .../main/kotlin/space/subread/dictionary/Audio.kt  | 119 ++++
 .../space/subread/dictionary/Dictionaries.kt       | 164 +++++
 .../space/subread/dictionary/LookupActivity.kt     | 250 ++++++++
 .../space/subread/dictionary/MainActivity.kt       | 281 +++++++++
 .../main/kotlin/space/subread/dictionary/Store.kt  |  43 ++
 app/src/main/res/drawable/icon.xml                 |   9 +
 app/src/main/res/values/strings.xml                |  62 ++
 app/src/main/res/values/styles.xml                 |  12 +
 build.gradle.kts                                   |   5 +
 core/build.gradle.kts                              |  31 +
 .../space/subread/dictionary/core/Deinflector.kt   | 283 +++++++++
 .../space/subread/dictionary/core/Glossary.kt      | 142 +++++
 .../kotlin/space/subread/dictionary/core/Kana.kt   |  18 +
 .../kotlin/space/subread/dictionary/core/Lookup.kt |  70 +++
 .../space/subread/dictionary/core/Yomitan.kt       | 171 ++++++
 .../space/subread/dictionary/core/CoreTest.kt      | 293 +++++++++
 gradle.properties                                  |   5 +
 gradle/libs.versions.toml                          |  27 +
 gradle/wrapper/gradle-wrapper.jar                  | Bin 0 -> 45457 bytes
 gradle/wrapper/gradle-wrapper.properties           |   9 +
 gradlew                                            | 251 ++++++++
 gradlew.bat                                        |  94 +++
 settings.gradle.kts                                |  26 +
 29 files changed, 3342 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..02bd9b7
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,20 @@
+.gradle/
+build/
+local.properties
+*.iml
+.idea/
+.kotlin/
+captures/
+.externalNativeBuild/
+.cxx/
+
+# Fixtures made from text that is not public domain stay on the machine
+# that generated them. Tests skip this directory when it is missing.
+core/src/test/resources/golden-local/
+
+# On-device test media. Bring your own pair; the test skips without it.
+app/src/androidTest/assets/local/
+
+
+# Python byte code
+__pycache__/
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..fe6b903
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,662 @@
+                    GNU AFFERO GENERAL PUBLIC LICENSE
+                       Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+our General Public Licenses are 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.
+
+  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.
+
+  Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+  A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate.  Many developers of free software are heartened and
+encouraged by the resulting cooperation.  However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+  The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community.  It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server.  Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+  An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals.  This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+  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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
+
+  Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software.  This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+  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 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 work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source.  For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code.  There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+  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 AGPL, see
+<https://www.gnu.org/licenses/>.
+
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..f791fa7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,70 @@
+# SubRead Dictionary
+
+A pop-up dictionary for Android that reads Yomitan dictionaries. Select a text
+in any app and choose "SubRead Dictionary" in the text selection menu, share a
+text to it, or send a word from
+[SubRead Overlay](https://github.com/equwal/subread-overlay). The pop-up
+opens over the app and shows each term at the start of the text, the longest
+first, with the reading, the pitch accent, the frequency, and a button for
+the audio. A tap on a character of the text looks up from there.
+
+Nothing leaves the device, except when a remote audio source is on.
+
+## How to use it
+
+1. Import a dictionary: a Yomitan `.zip` (JMdict, Jitendex, a pitch accent
+   dictionary, a frequency list). The app reads format 3. The order of the
+   dictionaries in the settings is the order in the pop-up.
+2. Local audio, optional: choose the `android.db` of the
+   [Local Audio Server for Yomitan](https://github.com/yomidevs/local-audio-yomichan),
+   the same file that AnkiConnect Android and Hoshi Reader use. The app copies
+   it into its folder. Or push it there with `adb`; the settings show the
+   folder. The order of the sources is a setting: `jpod, jpod_alternate,
+   nhk16, shinmeikai8, forvo`.
+3. Remote audio, optional and off by default: one URL per line, with `{term}`
+   and `{reading}`. A URL can answer with an audio file (JapanesePod101 is
+   the default line), or with the JSON list of a Local Audio Server on the
+   network: `http://192.168.1.2:5050/?term={term}&reading={reading}`. The
+   remote sources come after the local ones.
+
+In the pop-up, "Play" plays the first source that has the word. A long press
+on "Play" lists every source.
+
+## How it works
+
+`:core` is plain Kotlin, with no Android in it:
+
+- `YomitanZip` reads the zip as a stream, one term at a time.
+- `Deinflector` has the Japanese rules of Yomitan: 食べさせられた → 食べる,
+  with the word class of each step checked against the rules of the term.
+- `Lookup` tries each prefix of the text, the longest first, and each
+  dictionary form of it, in one query.
+- `Glossary` turns the structured content of a term into the simple HTML
+  that a `TextView` shows.
+
+`:app` has the SQLite store of the terms, the settings screen, the pop-up and
+the audio.
+
+## For other apps
+
+Send a text with any of these; the pop-up opens over your app:
+
+- `Intent.ACTION_PROCESS_TEXT` with `EXTRA_PROCESS_TEXT` (the text selection menu).
+- `Intent.ACTION_SEND`, `text/plain`, with `EXTRA_TEXT` (the share sheet).
+- The action `space.subread.dictionary.LOOKUP` with `EXTRA_TEXT`.
+
+## Build
+
+```
+./gradlew :core:test :app:assembleDebug
+./gradlew :app:connectedDebugAndroidTest   # the SQLite store, on a device
+```
+
+The device test installs the debug app again and removes its data: the
+imported dictionaries of the debug build are gone after it.
+
+`-PplayStore=true` leaves the Ko-fi link out of the build for Google Play.
+
+## Licence
+
+AGPL-3.0. See `LICENSE`.
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
new file mode 100644
index 0000000..b787331
--- /dev/null
+++ b/app/build.gradle.kts
@@ -0,0 +1,70 @@
+plugins {
+    alias(libs.plugins.android.application)
+}
+
+// Release signing comes from the environment, so the key never lives in the repository.
+val keystorePath = providers.environmentVariable("SUBREAD_KEYSTORE_FILE").orNull
+val keystorePassword = providers.environmentVariable("SUBREAD_KEYSTORE_PASSWORD").orNull
+val signingReady = !keystorePath.isNullOrBlank() && !keystorePassword.isNullOrBlank() &&
+    file(keystorePath).isFile
+
+android {
+    namespace = "space.subread.dictionary"
+    compileSdk = 36
+
+    // No list of dependencies, encrypted for Google alone, inside the app: F-Droid
+    // does not accept a part of the app that nobody else can read.
+    dependenciesInfo {
+        includeInApk = false
+        includeInBundle = false
+    }
+
+    defaultConfig {
+        applicationId = "space.subread.dictionary"
+        minSdk = 26
+        targetSdk = 36
+        // Plain numbers, in this file: F-Droid reads them from here to find a new release.
+        versionCode = 1
+        versionName = "0.1.0"
+        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
+
+        // A link to the Ko-fi page. Google Play is not given it (-PplayStore=true).
+        buildConfigField("boolean", "DONATE_LINK", (providers.gradleProperty("playStore").orNull != "true").toString())
+    }
+
+    if (signingReady) {
+        signingConfigs {
+            create("release") {
+                storeFile = file(keystorePath!!)
+                storePassword = keystorePassword
+                keyAlias = "subread"
+                keyPassword = keystorePassword
+            }
+        }
+    }
+
+    buildTypes {
+        debug { applicationIdSuffix = ".debug" }
+        release {
+            isMinifyEnabled = false
+            if (signingReady) signingConfig = signingConfigs.getByName("release")
+        }
+    }
+
+    compileOptions {
+        sourceCompatibility = JavaVersion.VERSION_17
+        targetCompatibility = JavaVersion.VERSION_17
+    }
+    buildFeatures { buildConfig = true }
+}
+
+dependencies {
+    implementation(project(":core"))
+    implementation(libs.androidx.core.ktx)
+    implementation(libs.gson)
+
+    androidTestImplementation(libs.junit)
+    androidTestImplementation(libs.androidx.test.runner)
+    androidTestImplementation(libs.androidx.test.junit)
+    androidTestImplementation(libs.androidx.test.core)
+}
diff --git a/app/src/androidTest/kotlin/space/subread/dictionary/DictionariesTest.kt b/app/src/androidTest/kotlin/space/subread/dictionary/DictionariesTest.kt
new file mode 100644
index 0000000..ea07378
--- /dev/null
+++ b/app/src/androidTest/kotlin/space/subread/dictionary/DictionariesTest.kt
@@ -0,0 +1,101 @@
+package space.subread.dictionary
+
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import space.subread.dictionary.core.DictionaryIndex
+import space.subread.dictionary.core.Lookup
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+import java.util.zip.ZipEntry
+import java.util.zip.ZipOutputStream
+
+/** The import into SQLite and the lookup through it, on a device. */
+@RunWith(AndroidJUnit4::class)
+class DictionariesTest {
+
+    private val context = ApplicationProvider.getApplicationContext<android.content.Context>()
+    private lateinit var dictionaries: Dictionaries
+
+    @Before
+    fun open() {
+        context.deleteDatabase("test.db")
+        dictionaries = Dictionaries(context, "test.db")
+    }
+
+    @After
+    fun close() {
+        dictionaries.close()
+        context.deleteDatabase("test.db")
+    }
+
+    private fun zip(vararg files: Pair<String, String>): ByteArray {
+        val bytes = ByteArrayOutputStream()
+        ZipOutputStream(bytes).use { out ->
+            for ((name, body) in files) {
+                out.putNextEntry(ZipEntry(name))
+                out.write(body.toByteArray())
+                out.closeEntry()
+            }
+        }
+        return bytes.toByteArray()
+    }
+
+    private val termBank = """[
+        ["食べる","たべる","v1","v1",10,["to eat"],1,"P"],
+        ["食べ物","たべもの","n","",5,["food"],2,""],
+        ["物","もの","n","",1,["thing"],3,""]
+    ]"""
+
+    private val metaBank = """[["食べる","freq",{"value":100,"displayValue":"100"}],["食べる","pitch",{"reading":"たべる","pitches":[{"position":2}]}]]"""
+
+    @Test
+    fun importThenLookup() {
+        val index = DictionaryIndex("Test", "1", 3)
+        val counts = ArrayList<Int>()
+        val info = dictionaries.import(index, ByteArrayInputStream(zip("term_bank_1.json" to termBank, "term_meta_bank_1.json" to metaBank))) { counts.add(it) }
+        // Three terms and two meta rows.
+        assertEquals(5, info.terms)
+        assertEquals(listOf(info), dictionaries.list())
+
+        val found = Lookup.find("食べ物を食べた", 4, dictionaries)
+        assertEquals("食べる", found.first().stored.term.expression)
+        assertEquals(listOf("past"), found.first().reasons)
+        // A kana text finds the reading.
+        assertEquals("食べ物", Lookup.find("たべもの", 0, dictionaries).first().stored.term.expression)
+
+        val meta = dictionaries.meta("食べる")
+        assertEquals(listOf("freq", "pitch"), meta.map { it.meta.mode })
+    }
+
+    @Test
+    fun aDisabledDictionaryIsNotSearched() {
+        val info = dictionaries.import(DictionaryIndex("Test", "1", 3), ByteArrayInputStream(zip("term_bank_1.json" to termBank))) {}
+        dictionaries.setEnabled(info.id, false)
+        assertTrue(Lookup.find("食べる", 0, dictionaries).isEmpty())
+        assertTrue(!dictionaries.anyEnabled())
+    }
+
+    @Test
+    fun deleteRemovesTheTermsToo() {
+        val info = dictionaries.import(DictionaryIndex("Test", "1", 3), ByteArrayInputStream(zip("term_bank_1.json" to termBank, "term_meta_bank_1.json" to metaBank))) {}
+        dictionaries.delete(info.id)
+        assertTrue(dictionaries.list().isEmpty())
+        assertTrue(dictionaries.terms(listOf("食べる")).isEmpty())
+        assertTrue(dictionaries.meta("食べる").isEmpty())
+    }
+
+    @Test
+    fun orderFollowsMoveUp() {
+        val a = dictionaries.import(DictionaryIndex("A", "1", 3), ByteArrayInputStream(zip("term_bank_1.json" to "[]"))) {}
+        val b = dictionaries.import(DictionaryIndex("B", "1", 3), ByteArrayInputStream(zip("term_bank_1.json" to "[]"))) {}
+        assertEquals(listOf(a.id, b.id), dictionaries.list().map { it.id })
+        dictionaries.moveUp(b.id)
+        assertEquals(listOf(b.id, a.id), dictionaries.list().map { it.id })
+    }
+}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..12d4bf8
--- /dev/null
+++ b/app/src/main/AndroidManifest.xml
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+    <!-- For the remote audio sources only. They are off until the user turns them on. -->
+    <uses-permission android:name="android.permission.INTERNET" />
+
+    <application
+        android:allowBackup="false"
+        android:icon="@drawable/icon"
+        android:label="@string/app_name"
+        android:supportsRtl="true"
+        android:theme="@android:style/Theme.DeviceDefault.Light.NoActionBar"
+        android:usesCleartextTraffic="true">
+
+        <!-- The settings: the dictionaries, the audio. -->
+        <activity
+            android:name=".MainActivity"
+            android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+
+        <!--
+            The pop-up. Three ways in: the text selection menu of Android ("SubRead Dictionary"
+            in the menu), the share sheet, and a plain intent from another app such as SubRead
+            Overlay. It has no task of its own, so it opens over the app that sent the text.
+        -->
+        <activity
+            android:name=".LookupActivity"
+            android:excludeFromRecents="true"
+            android:exported="true"
+            android:label="@string/lookup_label"
+            android:launchMode="singleTop"
+            android:taskAffinity=""
+            android:theme="@style/Popup">
+            <intent-filter>
+                <action android:name="android.intent.action.PROCESS_TEXT" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <data android:mimeType="text/plain" />
+            </intent-filter>
+            <intent-filter>
+                <action android:name="android.intent.action.SEND" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <data android:mimeType="text/plain" />
+            </intent-filter>
+            <intent-filter>
+                <action android:name="space.subread.dictionary.LOOKUP" />
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
+        </activity>
+    </application>
+</manifest>
diff --git a/app/src/main/kotlin/space/subread/dictionary/Audio.kt b/app/src/main/kotlin/space/subread/dictionary/Audio.kt
new file mode 100644
index 0000000..689bc51
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/dictionary/Audio.kt
@@ -0,0 +1,119 @@
+package space.subread.dictionary
+
+import android.content.Context
+import android.database.sqlite.SQLiteDatabase
+import android.media.MediaPlayer
+import com.google.gson.JsonParser
+import java.io.File
+import java.io.FileInputStream
+import java.net.HttpURLConnection
+import java.net.URL
+import java.net.URLEncoder
+
+/** One place that can have the audio of a term. The bytes are loaded when the user plays it. */
+class AudioSource(val name: String, val load: () -> ByteArray?)
+
+/**
+ * The android.db of the Local Audio Server for Yomitan. Two tables: `entries` gives the file of
+ * a term for each source, `android` holds the bytes of each file.
+ */
+class LocalAudio(private val file: File, private val sourceOrder: List<String>) {
+
+    fun exists() = file.isFile
+
+    fun sources(expression: String, reading: String): List<AudioSource> {
+        if (!file.isFile) return emptyList()
+        val db = runCatching { SQLiteDatabase.openDatabase(file.path, null, SQLiteDatabase.OPEN_READONLY) }.getOrNull() ?: return emptyList()
+        val kana = reading.ifEmpty { expression }
+        data class Row(val source: String, val speaker: String?, val display: String?, val file: String)
+        val rows = db.rawQuery(
+            "SELECT source, speaker, display, file FROM entries WHERE expression = ? AND (reading = ? OR reading IS NULL)",
+            arrayOf(expression, kana),
+        ).use { c ->
+            buildList { while (c.moveToNext()) add(Row(c.getString(0), c.getString(1), c.getString(2), c.getString(3))) }
+        }
+        val ordered = rows.sortedBy { sourceOrder.indexOf(it.source).let { i -> if (i < 0) sourceOrder.size else i } }
+        return ordered.map { row ->
+            val name = listOfNotNull(label(row.source), row.speaker, row.display).joinToString(" ")
+            AudioSource(name) {
+                db.rawQuery("SELECT data FROM android WHERE file = ? AND source = ?", arrayOf(row.file, row.source)).use { c ->
+                    if (c.moveToFirst()) c.getBlob(0) else null
+                }
+            }
+        }
+    }
+
+    private fun label(source: String) = when (source) {
+        "jpod" -> "JPod101"
+        "jpod_alternate" -> "JPod101 Alternate"
+        "nhk16" -> "NHK16"
+        "shinmeikai8" -> "Shinmeikai 8"
+        "forvo" -> "Forvo"
+        else -> source
+    }
+}
+
+/** Audio from a URL. A URL can answer with an audio file, or with the JSON source list of a Local Audio Server. */
+object RemoteAudio {
+
+    /** The size of the file that JapanesePod101 sends for a word it does not have. Yomitan skips it too. */
+    private const val JPOD_MISSING_SIZE = 52288
+
+    fun sources(templates: List<String>, expression: String, reading: String): List<AudioSource> = templates.map { template ->
+        val url = template
+            .replace("{term}", URLEncoder.encode(expression, "UTF-8"))
+            .replace("{reading}", URLEncoder.encode(reading.ifEmpty { expression }, "UTF-8"))
+        AudioSource(URL(url).host) { fetchAudio(url) }
+    }
+
+    private fun fetchAudio(url: String): ByteArray? {
+        val bytes = fetch(url) ?: return null
+        val text = if (bytes.size < 1_000_000) bytes.decodeToString().trimStart() else ""
+        if (text.startsWith("{")) {
+            // The JSON of a Local Audio Server: the first source that has bytes.
+            val list = runCatching { JsonParser.parseString(text).asJsonObject.getAsJsonArray("audioSources") }.getOrNull() ?: return null
+            for (source in list) {
+                val sourceUrl = source.asJsonObject.get("url")?.asString ?: continue
+                val audio = fetch(sourceUrl)
+                if (audio != null && audio.isNotEmpty()) return audio
+            }
+            return null
+        }
+        if (bytes.isEmpty() || bytes.size == JPOD_MISSING_SIZE) return null
+        return bytes
+    }
+
+    private fun fetch(url: String): ByteArray? = runCatching {
+        val connection = URL(url).openConnection() as HttpURLConnection
+        connection.connectTimeout = 8000
+        connection.readTimeout = 8000
+        try {
+            if (connection.responseCode != 200) null else connection.inputStream.use { it.readBytes() }
+        } finally {
+            connection.disconnect()
+        }
+    }.getOrNull()
+}
+
+/** Plays one audio file. The bytes go to a file in the cache: MediaPlayer wants a file descriptor. */
+class AudioPlayer(private val context: Context) {
+
+    private var player: MediaPlayer? = null
+
+    fun play(bytes: ByteArray) {
+        stop()
+        val file = File(context.cacheDir, "audio.tmp")
+        file.writeBytes(bytes)
+        player = MediaPlayer().apply {
+            FileInputStream(file).use { setDataSource(it.fd) }
+            setOnCompletionListener { stop() }
+            prepare()
+            start()
+        }
+    }
+
+    fun stop() {
+        player?.release()
+        player = null
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/dictionary/Dictionaries.kt b/app/src/main/kotlin/space/subread/dictionary/Dictionaries.kt
new file mode 100644
index 0000000..36f8fc5
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/dictionary/Dictionaries.kt
@@ -0,0 +1,164 @@
+package space.subread.dictionary
+
+import android.content.Context
+import android.database.sqlite.SQLiteDatabase
+import android.database.sqlite.SQLiteOpenHelper
+import androidx.core.database.sqlite.transaction
+import space.subread.dictionary.core.DictionaryIndex
+import space.subread.dictionary.core.DictionarySink
+import space.subread.dictionary.core.StoredTerm
+import space.subread.dictionary.core.Tag
+import space.subread.dictionary.core.Term
+import space.subread.dictionary.core.TermMeta
+import space.subread.dictionary.core.TermSource
+import space.subread.dictionary.core.YomitanZip
+import java.io.InputStream
+
+/** One imported dictionary. `terms` counts the term rows and the meta rows: a pitch or frequency dictionary has meta rows alone. */
+data class DictionaryInfo(val id: Long, val title: String, val revision: String, val position: Int, val enabled: Boolean, val terms: Int)
+
+/** A frequency or pitch entry, with the title of the dictionary it comes from. */
+data class StoredMeta(val dictionaryTitle: String, val meta: TermMeta)
+
+/**
+ * The imported dictionaries, in one SQLite database. The terms of every dictionary are in one
+ * table, so a lookup is one query. The rows keep the fields of the Yomitan format as they are.
+ */
+class Dictionaries(context: Context, name: String = "dictionaries.db") : SQLiteOpenHelper(context, name, null, 1), TermSource {
+
+    override fun onCreate(db: SQLiteDatabase) {
+        db.execSQL("CREATE TABLE dictionaries (id INTEGER PRIMARY KEY, title TEXT NOT NULL UNIQUE, revision TEXT NOT NULL, position INTEGER NOT NULL, enabled INTEGER NOT NULL DEFAULT 1)")
+        db.execSQL(
+            "CREATE TABLE terms (id INTEGER PRIMARY KEY, dictionary INTEGER NOT NULL, expression TEXT NOT NULL, reading TEXT NOT NULL, " +
+                "definition_tags TEXT NOT NULL, rules TEXT NOT NULL, score REAL NOT NULL, glossary TEXT NOT NULL, sequence INTEGER NOT NULL, term_tags TEXT NOT NULL)",
+        )
+        db.execSQL("CREATE INDEX terms_expression ON terms(expression)")
+        db.execSQL("CREATE INDEX terms_reading ON terms(reading)")
+        db.execSQL("CREATE INDEX terms_dictionary ON terms(dictionary)")
+        db.execSQL("CREATE TABLE meta (id INTEGER PRIMARY KEY, dictionary INTEGER NOT NULL, expression TEXT NOT NULL, mode TEXT NOT NULL, data TEXT NOT NULL)")
+        db.execSQL("CREATE INDEX meta_expression ON meta(expression)")
+        db.execSQL("CREATE INDEX meta_dictionary ON meta(dictionary)")
+    }
+
+    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) = Unit
+
+    fun list(): List<DictionaryInfo> = readableDatabase.rawQuery(
+        "SELECT d.id, d.title, d.revision, d.position, d.enabled, " +
+            "(SELECT COUNT(*) FROM terms t WHERE t.dictionary = d.id) + (SELECT COUNT(*) FROM meta m WHERE m.dictionary = d.id) " +
+            "FROM dictionaries d ORDER BY d.position",
+        null,
+    ).use { c ->
+        buildList {
+            while (c.moveToNext()) add(DictionaryInfo(c.getLong(0), c.getString(1), c.getString(2), c.getInt(3), c.getInt(4) != 0, c.getInt(5)))
+        }
+    }
+
+    fun hasTitle(title: String): Boolean = readableDatabase.rawQuery("SELECT 1 FROM dictionaries WHERE title = ?", arrayOf(title)).use { it.moveToFirst() }
+
+    /**
+     * Imports the banks of a zip, in one transaction: a failure half way leaves nothing. The
+     * progress callback gets the number of rows so far, terms and meta, from the import thread.
+     */
+    fun import(index: DictionaryIndex, zip: InputStream, progress: (Int) -> Unit): DictionaryInfo {
+        require(!hasTitle(index.title)) { "exists" }
+        return writableDatabase.transaction {
+            val db = this
+            val position = (db.rawQuery("SELECT MAX(position) FROM dictionaries", null).use { if (it.moveToFirst()) it.getInt(0) else 0 }) + 1
+            val id = db.compileStatement("INSERT INTO dictionaries (title, revision, position, enabled) VALUES (?, ?, ?, 1)").run {
+                bindString(1, index.title)
+                bindString(2, index.revision)
+                bindLong(3, position.toLong())
+                executeInsert()
+            }
+            val termInsert = db.compileStatement(
+                "INSERT INTO terms (dictionary, expression, reading, definition_tags, rules, score, glossary, sequence, term_tags) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
+            )
+            val metaInsert = db.compileStatement("INSERT INTO meta (dictionary, expression, mode, data) VALUES (?, ?, ?, ?)")
+            var count = 0
+            YomitanZip.readBanks(zip, object : DictionarySink {
+                override fun term(term: Term) {
+                    termInsert.bindLong(1, id)
+                    termInsert.bindString(2, term.expression)
+                    // A term with no reading is read as it is written. The stored reading is the text a kana lookup finds.
+                    termInsert.bindString(3, term.reading.ifEmpty { term.expression })
+                    termInsert.bindString(4, term.definitionTags)
+                    termInsert.bindString(5, term.rules)
+                    termInsert.bindDouble(6, term.score)
+                    termInsert.bindString(7, term.glossary)
+                    termInsert.bindLong(8, term.sequence)
+                    termInsert.bindString(9, term.termTags)
+                    termInsert.executeInsert()
+                    if (++count % 1000 == 0) progress(count)
+                }
+
+                override fun termMeta(meta: TermMeta) {
+                    metaInsert.bindLong(1, id)
+                    metaInsert.bindString(2, meta.expression)
+                    metaInsert.bindString(3, meta.mode)
+                    metaInsert.bindString(4, meta.data)
+                    metaInsert.executeInsert()
+                    if (++count % 1000 == 0) progress(count)
+                }
+
+                // The tag bank gives the notes of a tag. The pop-up shows the tag names alone.
+                override fun tag(tag: Tag) = Unit
+            })
+            DictionaryInfo(id, index.title, index.revision, position, true, count)
+        }
+    }
+
+    fun delete(id: Long) {
+        writableDatabase.transaction {
+            delete("terms", "dictionary = ?", arrayOf(id.toString()))
+            delete("meta", "dictionary = ?", arrayOf(id.toString()))
+            delete("dictionaries", "id = ?", arrayOf(id.toString()))
+        }
+    }
+
+    fun setEnabled(id: Long, enabled: Boolean) {
+        writableDatabase.execSQL("UPDATE dictionaries SET enabled = ? WHERE id = ?", arrayOf<Any>(if (enabled) 1 else 0, id))
+    }
+
+    /** Moves a dictionary one place up in the order. The first one stays. */
+    fun moveUp(id: Long) {
+        val all = list()
+        val i = all.indexOfFirst { it.id == id }
+        if (i <= 0) return
+        val db = writableDatabase
+        db.execSQL("UPDATE dictionaries SET position = ? WHERE id = ?", arrayOf<Any>(all[i - 1].position, id))
+        db.execSQL("UPDATE dictionaries SET position = ? WHERE id = ?", arrayOf<Any>(all[i].position, all[i - 1].id))
+    }
+
+    override fun terms(texts: Collection<String>): List<StoredTerm> {
+        val db = readableDatabase
+        val out = ArrayList<StoredTerm>()
+        // SQLite takes a limited number of parameters in one statement.
+        for (chunk in texts.chunked(400)) {
+            val marks = chunk.joinToString(",") { "?" }
+            val args = (chunk + chunk).toTypedArray()
+            db.rawQuery(
+                "SELECT t.expression, t.reading, t.definition_tags, t.rules, t.score, t.glossary, t.sequence, t.term_tags, d.id, d.title, d.position " +
+                    "FROM terms t JOIN dictionaries d ON d.id = t.dictionary " +
+                    "WHERE d.enabled = 1 AND (t.expression IN ($marks) OR t.reading IN ($marks))",
+                args,
+            ).use { c ->
+                while (c.moveToNext()) {
+                    val term = Term(c.getString(0), c.getString(1), c.getString(2), c.getString(3), c.getDouble(4), c.getString(5), c.getLong(6), c.getString(7))
+                    out.add(StoredTerm(c.getLong(8), c.getString(9), c.getInt(10), term))
+                }
+            }
+        }
+        return out
+    }
+
+    /** The frequency and pitch entries of an expression, from the enabled dictionaries in their order. */
+    fun meta(expression: String): List<StoredMeta> = readableDatabase.rawQuery(
+        "SELECT m.expression, m.mode, m.data, d.title FROM meta m JOIN dictionaries d ON d.id = m.dictionary " +
+            "WHERE d.enabled = 1 AND m.expression = ? ORDER BY d.position",
+        arrayOf(expression),
+    ).use { c ->
+        buildList { while (c.moveToNext()) add(StoredMeta(c.getString(3), TermMeta(c.getString(0), c.getString(1), c.getString(2)))) }
+    }
+
+    fun anyEnabled(): Boolean = readableDatabase.rawQuery("SELECT 1 FROM dictionaries WHERE enabled = 1", null).use { it.moveToFirst() }
+}
diff --git a/app/src/main/kotlin/space/subread/dictionary/LookupActivity.kt b/app/src/main/kotlin/space/subread/dictionary/LookupActivity.kt
new file mode 100644
index 0000000..8f6e275
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/dictionary/LookupActivity.kt
@@ -0,0 +1,250 @@
+package space.subread.dictionary
+
+import android.annotation.SuppressLint
+import android.app.Activity
+import android.app.AlertDialog
+import android.content.Intent
+import android.graphics.Color
+import android.graphics.Typeface
+import android.os.Bundle
+import android.text.Html
+import android.text.SpannableString
+import android.text.Spanned
+import android.text.method.LinkMovementMethod
+import android.text.style.BackgroundColorSpan
+import android.view.Gravity
+import android.view.MotionEvent
+import android.view.View
+import android.view.ViewGroup
+import android.view.WindowManager
+import android.widget.Button
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
+import android.widget.Toast
+import space.subread.dictionary.core.Glossary
+import space.subread.dictionary.core.Lookup
+import space.subread.dictionary.core.Match
+import kotlin.concurrent.thread
+
+/**
+ * The pop-up. It takes a text from the text selection menu, from the share sheet, or from an
+ * intent, and shows the terms at the scan position: the longest first. A tap on a character of
+ * the text moves the scan position there.
+ */
+class LookupActivity : Activity() {
+
+    private lateinit var store: Store
+    private lateinit var dictionaries: Dictionaries
+    private lateinit var player: AudioPlayer
+    private lateinit var textView: TextView
+    private lateinit var results: LinearLayout
+    private var text = ""
+    private var offset = 0
+    private var generation = 0
+
+    // The touch listener finds the character under the finger; it calls performClick itself.
+    @SuppressLint("ClickableViewAccessibility")
+    override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+        store = Store(this)
+        dictionaries = Dictionaries(this)
+        player = AudioPlayer(this)
+
+        // A panel at the bottom, over the app that sent the text. The height is fixed, so the
+        // panel does not grow with the results: they scroll inside it.
+        val height = (resources.displayMetrics.heightPixels * 0.6).toInt()
+        window.attributes = window.attributes.apply {
+            width = ViewGroup.LayoutParams.MATCH_PARENT
+            this.height = height
+            gravity = Gravity.BOTTOM
+        }
+        window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
+
+        textView = TextView(this).apply {
+            textSize = store.textSizeSp + 3
+            setTextColor(Color.BLACK)
+            maxLines = 4
+            setPadding(dp(16), dp(12), dp(16), dp(8))
+            setOnTouchListener { view, event ->
+                if (event.action == MotionEvent.ACTION_UP) {
+                    val at = (view as TextView).getOffsetForPosition(event.x, event.y)
+                    if (at in text.indices) scan(at)
+                    view.performClick()
+                }
+                true
+            }
+        }
+        results = LinearLayout(this).apply {
+            orientation = LinearLayout.VERTICAL
+            setPadding(dp(16), 0, dp(16), dp(16))
+        }
+        val bar = LinearLayout(this).apply {
+            gravity = Gravity.END
+            addView(smallButton(getString(R.string.settings)) { startActivity(Intent(this@LookupActivity, MainActivity::class.java)) })
+            addView(smallButton(getString(R.string.close)) { finish() })
+        }
+        setContentView(
+            LinearLayout(this).apply {
+                orientation = LinearLayout.VERTICAL
+                setBackgroundColor(Color.WHITE)
+                addView(bar, LinearLayout.LayoutParams(-1, -2))
+                addView(textView, LinearLayout.LayoutParams(-1, -2))
+                addView(View(this@LookupActivity).apply { setBackgroundColor(Color.LTGRAY) }, LinearLayout.LayoutParams(-1, dp(1)))
+                addView(ScrollView(this@LookupActivity).apply { addView(results) }, LinearLayout.LayoutParams(-1, 0, 1f))
+            },
+            ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height),
+        )
+        take(intent)
+    }
+
+    override fun onNewIntent(intent: Intent) {
+        super.onNewIntent(intent)
+        setIntent(intent)
+        take(intent)
+    }
+
+    override fun onDestroy() {
+        player.stop()
+        dictionaries.close()
+        super.onDestroy()
+    }
+
+    /** The text of the intent, from whichever of the three ways in. */
+    private fun take(intent: Intent) {
+        text = (intent.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT) ?: intent.getCharSequenceExtra(Intent.EXTRA_TEXT) ?: "")
+            .toString().trim()
+        if (text.isEmpty()) {
+            Toast.makeText(this, R.string.no_text, Toast.LENGTH_SHORT).show()
+            finish()
+            return
+        }
+        scan(0)
+    }
+
+    private fun scan(at: Int) {
+        offset = at
+        val shown = SpannableString(text)
+        textView.text = shown
+        val run = ++generation
+        thread {
+            val found = if (dictionaries.anyEnabled()) Lookup.find(text, at, dictionaries) else null
+            val metas = found.orEmpty().map { it.stored.term.expression }.distinct().associateWith { dictionaries.meta(it) }
+            runOnUiThread { if (run == generation) show(found, metas) }
+        }
+    }
+
+    private fun show(found: List<Match>?, metas: Map<String, List<StoredMeta>>) {
+        results.removeAllViews()
+        if (found == null) {
+            note(getString(R.string.no_dictionaries))
+            return
+        }
+        if (found.isEmpty()) {
+            note(getString(R.string.no_results))
+            return
+        }
+        // The longest match is marked in the text.
+        val shown = SpannableString(text)
+        shown.setSpan(BackgroundColorSpan(0xFFFFE082.toInt()), offset, offset + found.first().length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
+        textView.text = shown
+
+        // One card per expression and reading, with the entries of each dictionary inside it.
+        val groups = found.groupBy { it.stored.term.expression to it.stored.term.reading }
+        for ((key, matches) in groups) {
+            val (expression, reading) = key
+            results.addView(View(this).apply { setBackgroundColor(Color.LTGRAY) }, LinearLayout.LayoutParams(-1, dp(1)).apply { topMargin = dp(10) })
+            results.addView(LinearLayout(this).apply {
+                gravity = Gravity.CENTER_VERTICAL
+                addView(TextView(this@LookupActivity).apply {
+                    text = if (reading.isEmpty() || reading == expression) expression else "$expression【$reading】"
+                    textSize = store.textSizeSp + 5
+                    setTypeface(typeface, Typeface.BOLD)
+                    setTextColor(Color.BLACK)
+                }, LinearLayout.LayoutParams(0, -2, 1f))
+                addView(smallButton("▶ " + getString(R.string.audio_play)) { play(expression, reading, choose = false) }.apply {
+                    setOnLongClickListener { play(expression, reading, choose = true); true }
+                })
+            }, LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(6) })
+
+            val reasons = matches.first().reasons
+            val meta = metas[expression].orEmpty().filter { m ->
+                val forReading = when (m.meta.mode) { "freq" -> Glossary.frequencyReading(m.meta.data); "pitch" -> Glossary.pitchReading(m.meta.data); else -> null }
+                forReading == null || forReading == reading || reading.isEmpty()
+            }
+            val line = buildList {
+                if (reasons.isNotEmpty()) add(reasons.joinToString(" ‹ "))
+                for (m in meta) when (m.meta.mode) {
+                    "freq" -> add("${m.dictionaryTitle}: ${Glossary.frequencyText(m.meta.data)}")
+                    "pitch" -> add(Glossary.pitchText(m.meta.data))
+                }
+            }
+            if (line.isNotEmpty()) note(line.joinToString("   "), color = Color.DKGRAY, size = store.textSizeSp - 3)
+
+            for (match in matches) {
+                val term = match.stored.term
+                val tags = (term.definitionTags.split(' ') + term.termTags.split(' ')).filter { it.isNotEmpty() }.distinct()
+                note(
+                    listOf(match.stored.dictionaryTitle).plus(tags).joinToString("  "),
+                    color = Color.GRAY,
+                    size = store.textSizeSp - 4,
+                    top = 6,
+                )
+                results.addView(TextView(this).apply {
+                    text = Html.fromHtml(Glossary.toHtml(term.glossary), Html.FROM_HTML_MODE_COMPACT)
+                    textSize = store.textSizeSp
+                    setTextColor(Color.BLACK)
+                    movementMethod = LinkMovementMethod.getInstance()
+                }, LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(2) })
+            }
+        }
+    }
+
+    /** Plays the first source that has audio: the local ones in their order, then the remote ones. */
+    private fun play(expression: String, reading: String, choose: Boolean) {
+        thread {
+            val sources = LocalAudio(store.localAudioFile, store.localSources.split(',').map { it.trim() }).sources(expression, reading) +
+                if (store.remoteEnabled) RemoteAudio.sources(store.remoteUrls.lines().map { it.trim() }.filter { it.isNotEmpty() }, expression, reading) else emptyList()
+            if (choose) {
+                runOnUiThread {
+                    if (sources.isEmpty()) toast(getString(R.string.no_audio)) else {
+                        AlertDialog.Builder(this).setItems(sources.map { it.name }.toTypedArray()) { _, i -> thread { playFirst(listOf(sources[i])) } }.show()
+                    }
+                }
+            } else {
+                playFirst(sources)
+            }
+        }
+    }
+
+    private fun playFirst(sources: List<AudioSource>) {
+        for (source in sources) {
+            val bytes = runCatching { source.load() }.getOrNull() ?: continue
+            runOnUiThread {
+                runCatching { player.play(bytes) }.onFailure { toast(getString(R.string.audio_failed, it.message ?: "")) }
+            }
+            return
+        }
+        runOnUiThread { toast(getString(R.string.no_audio)) }
+    }
+
+    private fun toast(message: String) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
+
+    private fun note(value: String, color: Int = Color.BLACK, size: Float = store.textSizeSp, top: Int = 8) = results.addView(
+        TextView(this).apply {
+            text = value
+            textSize = size
+            setTextColor(color)
+        },
+        LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(top) },
+    )
+
+    private fun smallButton(label: String, onClick: () -> Unit) = Button(this).apply {
+        text = label
+        isAllCaps = false
+        textSize = 13f
+        setOnClickListener { onClick() }
+    }
+
+    private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
+}
diff --git a/app/src/main/kotlin/space/subread/dictionary/MainActivity.kt b/app/src/main/kotlin/space/subread/dictionary/MainActivity.kt
new file mode 100644
index 0000000..7656408
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/dictionary/MainActivity.kt
@@ -0,0 +1,281 @@
+package space.subread.dictionary
+
+import android.annotation.SuppressLint
+import android.app.Activity
+import android.app.AlertDialog
+import android.content.Intent
+import android.graphics.Color
+import android.graphics.Typeface
+import android.net.Uri
+import android.os.Bundle
+import android.provider.OpenableColumns
+import android.text.InputType
+import android.view.View
+import android.widget.Button
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
+import android.widget.Toast
+import androidx.core.net.toUri
+import space.subread.dictionary.core.DictionaryFormatException
+import space.subread.dictionary.core.YomitanZip
+import java.io.File
+import kotlin.concurrent.thread
+
+/**
+ * The settings, and the one screen that opens from the launcher: the dictionaries, the local
+ * audio, the remote audio, the text size, and a field to try a lookup.
+ */
+class MainActivity : Activity() {
+
+    private lateinit var store: Store
+    private lateinit var dictionaries: Dictionaries
+    private lateinit var content: LinearLayout
+
+    override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+        store = Store(this)
+        dictionaries = Dictionaries(this)
+        content = LinearLayout(this).apply {
+            orientation = LinearLayout.VERTICAL
+            setPadding(dp(20), dp(20), dp(20), dp(20))
+            setBackgroundColor(Color.WHITE)
+        }
+        setContentView(ScrollView(this).apply {
+            fitsSystemWindows = true
+            setBackgroundColor(Color.WHITE)
+            addView(content)
+        })
+    }
+
+    override fun onResume() {
+        super.onResume()
+        draw()
+    }
+
+    override fun onDestroy() {
+        dictionaries.close()
+        super.onDestroy()
+    }
+
+    private fun draw() {
+        content.removeAllViews()
+        title(getString(R.string.app_name))
+        note(getString(R.string.about))
+        note(getString(R.string.privacy))
+
+        // 1. Dictionaries
+        step(R.string.step_dictionaries, getString(R.string.step_dictionaries_why), getString(R.string.import_dictionary)) {
+            startActivityForResult(
+                Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*"),
+                PICK_DICTIONARY,
+            )
+        }
+        val list = dictionaries.list()
+        if (list.isEmpty()) note(getString(R.string.dictionaries_none))
+        for (dictionary in list) {
+            note(
+                resources.getQuantityString(R.plurals.dictionary_terms, dictionary.terms, dictionary.title, dictionary.terms),
+                color = if (dictionary.enabled) Color.BLACK else Color.GRAY,
+            )
+            row(
+                button(getString(if (dictionary.enabled) R.string.disable else R.string.enable)) {
+                    dictionaries.setEnabled(dictionary.id, !dictionary.enabled)
+                    draw()
+                },
+                button(getString(R.string.up)) {
+                    dictionaries.moveUp(dictionary.id)
+                    draw()
+                },
+                button(getString(R.string.delete)) {
+                    AlertDialog.Builder(this).setMessage(getString(R.string.delete_ask, dictionary.title))
+                        .setPositiveButton(R.string.delete) { _, _ -> thread { dictionaries.delete(dictionary.id); runOnUiThread { draw() } } }
+                        .setNegativeButton(android.R.string.cancel, null).show()
+                },
+            )
+        }
+
+        // 2. Local audio
+        val audio = store.localAudioFile
+        step(R.string.step_local_audio, getString(R.string.step_local_audio_why), getString(R.string.local_audio_choose)) {
+            startActivityForResult(
+                Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*"),
+                PICK_AUDIO,
+            )
+        }
+        if (audio.isFile) {
+            note(getString(R.string.local_audio_have, size(audio.length())))
+            content.addView(button(getString(R.string.local_audio_remove)) { audio.delete(); draw() }, LinearLayout.LayoutParams(-2, -2))
+        } else {
+            note(getString(R.string.local_audio_none))
+        }
+        note(getString(R.string.local_audio_folder, audio.parent ?: ""), color = Color.DKGRAY, size = 13f)
+        note(getString(R.string.local_audio_sources), top = 12)
+        val sources = field(store.localSources, single = true)
+        content.addView(button(getString(R.string.save)) {
+            store.localSources = sources.text.toString()
+            toast(getString(R.string.saved))
+        }, LinearLayout.LayoutParams(-2, -2))
+
+        // 3. Remote audio
+        val remote = store.remoteEnabled
+        step(
+            R.string.step_remote_audio,
+            getString(R.string.step_remote_audio_why) + "\n\n" + getString(if (remote) R.string.remote_audio_on else R.string.remote_audio_off),
+            getString(if (remote) R.string.turn_off else R.string.turn_on),
+        ) {
+            store.remoteEnabled = !remote
+            draw()
+        }
+        val urls = field(store.remoteUrls, single = false)
+        content.addView(button(getString(R.string.save)) {
+            store.remoteUrls = urls.text.toString()
+            toast(getString(R.string.saved))
+        }, LinearLayout.LayoutParams(-2, -2))
+
+        // 4. Text size
+        step(R.string.step_size, "${store.textSizeSp.toInt()} sp", null) {}
+        row(button("−") { store.textSizeSp -= 1f; draw() }, button("+") { store.textSizeSp += 1f; draw() })
+
+        // 5. Try it
+        step(R.string.step_try, "", null) {}
+        val tryField = field("", single = true).apply { hint = getString(R.string.try_hint) }
+        content.addView(button(getString(R.string.look_up)) {
+            startActivity(Intent(this, LookupActivity::class.java).setAction(LOOKUP).putExtra(Intent.EXTRA_TEXT, tryField.text.toString()))
+        }, LinearLayout.LayoutParams(-2, -2))
+
+        val overlay = packageManager.getLaunchIntentForPackage(OVERLAY_PACKAGE)
+        if (overlay != null) content.addView(button(getString(R.string.open_overlay)) { runCatching { startActivity(overlay) } }, wide(top = 24))
+        if (BuildConfig.DONATE_LINK) content.addView(button(getString(R.string.donate)) { open(KOFI) }, wide())
+    }
+
+    @Deprecated("The platform Activity has no other result API, and this app has no AndroidX activity.")
+    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+        val uri = data?.data
+        if (resultCode != RESULT_OK || uri == null) return
+        when (requestCode) {
+            PICK_DICTIONARY -> importDictionary(uri)
+            PICK_AUDIO -> copyAudio(uri)
+        }
+    }
+
+    /** Reads the index, then the banks, on a thread. A dialog shows the count. */
+    private fun importDictionary(uri: Uri) {
+        val dialog = AlertDialog.Builder(this).setMessage(displayName(uri)).setCancelable(false).show()
+        thread {
+            val result = runCatching {
+                val index = contentResolver.openInputStream(uri)!!.use { YomitanZip.readIndex(it) }
+                if (index.format != 3) throw DictionaryFormatException(getString(R.string.import_format, index.format))
+                if (dictionaries.hasTitle(index.title)) throw DictionaryFormatException(getString(R.string.import_exists))
+                contentResolver.openInputStream(uri)!!.use { zip ->
+                    dictionaries.import(index, zip) { count -> runOnUiThread { dialog.setMessage(getString(R.string.importing, index.title, count)) } }
+                }
+            }
+            runOnUiThread {
+                dialog.dismiss()
+                result.onFailure { toast(getString(R.string.import_failed, it.message ?: it.javaClass.simpleName)) }
+                draw()
+            }
+        }
+    }
+
+    /** Copies the android.db into the app folder. It can be gigabytes, so the dialog shows the size so far. */
+    private fun copyAudio(uri: Uri) {
+        val target = store.localAudioFile
+        val dialog = AlertDialog.Builder(this).setMessage(getString(R.string.local_audio_copying, "0 MB")).setCancelable(false).show()
+        thread {
+            val result = runCatching {
+                val partial = File(target.path + ".part")
+                contentResolver.openInputStream(uri)!!.use { input ->
+                    partial.outputStream().use { output ->
+                        val buffer = ByteArray(1 shl 20)
+                        var total = 0L
+                        while (true) {
+                            val n = input.read(buffer)
+                            if (n < 0) break
+                            output.write(buffer, 0, n)
+                            total += n
+                            if (total % (32L shl 20) < (1 shl 20)) runOnUiThread { dialog.setMessage(getString(R.string.local_audio_copying, size(total))) }
+                        }
+                    }
+                }
+                check(partial.renameTo(target)) { "rename" }
+            }
+            runOnUiThread {
+                dialog.dismiss()
+                result.onFailure { toast(getString(R.string.import_failed, it.message ?: it.javaClass.simpleName)) }
+                draw()
+            }
+        }
+    }
+
+    private fun displayName(uri: Uri): String =
+        contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use {
+            if (it.moveToFirst()) it.getString(0) else null
+        } ?: uri.lastPathSegment.orEmpty()
+
+    private fun size(bytes: Long) = "%.0f MB".format(bytes / 1048576.0)
+
+    private fun open(link: String) {
+        runCatching { startActivity(Intent(Intent.ACTION_VIEW, link.toUri())) }
+    }
+
+    private fun toast(message: String) = Toast.makeText(this, message, Toast.LENGTH_LONG).show()
+
+    // The screen is built in code: a few rows do not need a layout file each.
+
+    private fun title(value: String) = content.addView(TextView(this).apply {
+        text = value
+        textSize = 26f
+        setTypeface(typeface, Typeface.BOLD)
+        setTextColor(Color.BLACK)
+    })
+
+    private fun note(value: String, top: Int = 8, color: Int = Color.BLACK, size: Float = 15f) = content.addView(TextView(this).apply {
+        text = value
+        textSize = size
+        setTextColor(color)
+    }, wide(top))
+
+    private fun field(value: String, single: Boolean) = EditText(this).apply {
+        setText(value)
+        setTextColor(Color.BLACK)
+        textSize = 14f
+        inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or if (single) 0 else InputType.TYPE_TEXT_FLAG_MULTI_LINE
+        isSingleLine = single
+    }.also { content.addView(it, wide()) }
+
+    @SuppressLint("SetTextI18n")
+    private fun step(name: Int, detail: String, action: String?, onAction: () -> Unit) {
+        content.addView(View(this).apply { setBackgroundColor(Color.BLACK) }, LinearLayout.LayoutParams(-1, dp(1)).apply { topMargin = dp(16) })
+        content.addView(TextView(this).apply {
+            text = getString(name)
+            textSize = 18f
+            setTypeface(typeface, Typeface.BOLD)
+            setTextColor(Color.BLACK)
+        }, wide(top = 12))
+        if (detail.isNotEmpty()) note(detail, top = 4)
+        if (action != null) content.addView(button(action, onAction), LinearLayout.LayoutParams(-2, -2))
+    }
+
+    private fun row(vararg views: View) = content.addView(LinearLayout(this).apply { views.forEach { addView(it) } })
+
+    private fun button(label: String, onClick: () -> Unit) = Button(this).apply {
+        text = label
+        isAllCaps = false
+        setOnClickListener { onClick() }
+    }
+
+    private fun wide(top: Int = 8) = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(top) }
+
+    private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
+
+    private companion object {
+        const val PICK_DICTIONARY = 1
+        const val PICK_AUDIO = 2
+        const val LOOKUP = "space.subread.dictionary.LOOKUP"
+        const val OVERLAY_PACKAGE = "space.subread.overlay"
+        const val KOFI = "https://ko-fi.com/truex"
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/dictionary/Store.kt b/app/src/main/kotlin/space/subread/dictionary/Store.kt
new file mode 100644
index 0000000..b08e1e2
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/dictionary/Store.kt
@@ -0,0 +1,43 @@
+package space.subread.dictionary
+
+import android.content.Context
+import androidx.core.content.edit
+import java.io.File
+
+/** What the user chose. It stays when the app stops. */
+class Store(private val context: Context) {
+
+    private val prefs = context.getSharedPreferences("dictionary", Context.MODE_PRIVATE)
+
+    /** The sources of the local audio, in the order to try them. The names are the folder names of the Local Audio Server. */
+    var localSources: String
+        get() = prefs.getString("local_sources", DEFAULT_LOCAL_SOURCES) ?: DEFAULT_LOCAL_SOURCES
+        set(value) = prefs.edit { putString("local_sources", value) }
+
+    /** The remote audio URLs, one per line, with {term} and {reading}. */
+    var remoteUrls: String
+        get() = prefs.getString("remote_urls", DEFAULT_REMOTE_URLS) ?: DEFAULT_REMOTE_URLS
+        set(value) = prefs.edit { putString("remote_urls", value) }
+
+    /** Off until the user turns it on: a remote source sends the word to a server. */
+    var remoteEnabled: Boolean
+        get() = prefs.getBoolean("remote_enabled", false)
+        set(value) = prefs.edit { putBoolean("remote_enabled", value) }
+
+    var textSizeSp: Float
+        get() = prefs.getFloat("text_size", 17f)
+        set(value) = prefs.edit { putFloat("text_size", value.coerceIn(11f, 40f)) }
+
+    /**
+     * The android.db of the local audio. In the app folder on the external storage: `adb push` and
+     * a file manager with a USB cable can reach it, and the app needs no permission for it.
+     */
+    val localAudioFile: File
+        get() = File(context.getExternalFilesDir(null) ?: context.filesDir, "android.db")
+
+    companion object {
+        const val DEFAULT_LOCAL_SOURCES = "jpod, jpod_alternate, nhk16, shinmeikai8, forvo"
+        const val DEFAULT_REMOTE_URLS =
+            "https://assets.languagepod101.com/dictionary/japanese/audiomp3.php?kanji={term}&kana={reading}"
+    }
+}
diff --git a/app/src/main/res/drawable/icon.xml b/app/src/main/res/drawable/icon.xml
new file mode 100644
index 0000000..8df2a55
--- /dev/null
+++ b/app/src/main/res/drawable/icon.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
+    <path android:fillColor="#FFFFFF" android:pathData="M0,0h108v108h-108z" />
+    <!-- A book: two pages and a spine. -->
+    <path android:fillColor="#111111" android:pathData="M18,24h34v60h-34z M56,24h34v60h-34z" />
+    <path android:fillColor="#FFFFFF" android:pathData="M24,34h22v4h-22z M24,44h22v4h-22z M24,54h14v4h-14z M62,34h22v4h-22z M62,44h22v4h-22z M62,54h14v4h-14z" />
+    <path android:fillColor="#111111" android:pathData="M51,20h6v68h-6z" />
+</vector>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..175addd
--- /dev/null
+++ b/app/src/main/res/values/strings.xml
@@ -0,0 +1,62 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="app_name">SubRead Dictionary</string>
+    <string name="lookup_label">SubRead Dictionary</string>
+
+    <string name="about">A pop-up dictionary for Yomitan dictionaries. Select a text in any app and choose "SubRead Dictionary" in the menu, share a text to it, or send a word from SubRead Overlay. The pop-up shows each term at the start of the text, the longest first, with the reading, the pitch accent, the frequency and the audio.</string>
+    <string name="privacy">Nothing leaves the device, except when a remote audio source is on: then the word goes to that server.</string>
+
+    <string name="step_dictionaries">1. Dictionaries</string>
+    <string name="step_dictionaries_why">Yomitan dictionaries, as .zip files: JMdict, Jitendex, a pitch accent dictionary, a frequency list. The order here is the order in the pop-up.</string>
+    <string name="dictionaries_none">No dictionary yet.</string>
+    <string name="import_dictionary">Import a dictionary (.zip)</string>
+    <string name="importing">Importing %1$s… rows so far: %2$d</string>
+    <string name="import_failed">The import failed: %1$s</string>
+    <string name="import_exists">A dictionary with this title is already imported. Delete it first.</string>
+    <string name="import_format">This dictionary has format %1$d. The app reads format 3.</string>
+    <plurals name="dictionary_terms">
+        <item quantity="one">%1$s — %2$d entry</item>
+        <item quantity="other">%1$s — %2$d entries</item>
+    </plurals>
+    <string name="enable">Enable</string>
+    <string name="disable">Disable</string>
+    <string name="up">↑</string>
+    <string name="delete">Delete</string>
+    <string name="delete_ask">Delete %1$s?</string>
+
+    <string name="step_local_audio">2. Local audio</string>
+    <string name="step_local_audio_why">The android.db of the Local Audio Server for Yomitan, the same file that AnkiConnect Android and Hoshi Reader use. Choose the file; the app copies it. Or push it with adb to the folder below.</string>
+    <string name="local_audio_none">No android.db yet.</string>
+    <string name="local_audio_have">android.db, %1$s</string>
+    <string name="local_audio_choose">Choose android.db</string>
+    <string name="local_audio_copying">Copying android.db: %1$s</string>
+    <string name="local_audio_remove">Remove</string>
+    <string name="local_audio_sources">Order of the sources, comma separated</string>
+    <string name="local_audio_folder">Folder for adb push: %1$s</string>
+
+    <string name="step_remote_audio">3. Remote audio</string>
+    <string name="step_remote_audio_why">One URL per line. {term} and {reading} are replaced. A URL can give an audio file, or the JSON list of a Local Audio Server on the network (http://192.168.1.2:5050/?term={term}&amp;reading={reading}). Used after the local audio.</string>
+    <string name="remote_audio_on">On</string>
+    <string name="remote_audio_off">Off</string>
+    <string name="turn_on">Turn on</string>
+    <string name="turn_off">Turn off</string>
+    <string name="save">Save</string>
+    <string name="saved">Saved.</string>
+
+    <string name="step_size">4. Text size</string>
+    <string name="step_try">5. Try it</string>
+    <string name="try_hint">Type a text</string>
+    <string name="look_up">Look up</string>
+
+    <string name="open_overlay">Open SubRead Overlay</string>
+    <string name="donate">Support the app on Ko-fi</string>
+
+    <string name="no_text">The text is empty.</string>
+    <string name="no_results">No term found. Tap a character to look up from there.</string>
+    <string name="no_dictionaries">No dictionary is enabled. Open the app to import one.</string>
+    <string name="no_audio">No audio for this term.</string>
+    <string name="audio_play">Play</string>
+    <string name="audio_failed">The audio did not play: %1$s</string>
+    <string name="settings">Settings</string>
+    <string name="close">Close</string>
+</resources>
diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml
new file mode 100644
index 0000000..52c952c
--- /dev/null
+++ b/app/src/main/res/values/styles.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <!-- The pop-up: a floating panel over the app that sent the text. A tap outside closes it. -->
+    <style name="Popup" parent="@android:style/Theme.DeviceDefault.Light.Dialog.NoActionBar">
+        <item name="android:windowIsFloating">true</item>
+        <item name="android:windowNoTitle">true</item>
+        <item name="android:windowBackground">@android:color/white</item>
+        <item name="android:backgroundDimEnabled">false</item>
+        <item name="android:windowCloseOnTouchOutside">true</item>
+        <item name="android:windowAnimationStyle">@null</item>
+    </style>
+</resources>
diff --git a/build.gradle.kts b/build.gradle.kts
new file mode 100644
index 0000000..6ea42bf
--- /dev/null
+++ b/build.gradle.kts
@@ -0,0 +1,5 @@
+// Plugin versions live in gradle/libs.versions.toml; each module applies its own.
+plugins {
+    alias(libs.plugins.kotlin.jvm) apply false
+    alias(libs.plugins.android.application) apply false
+}
diff --git a/core/build.gradle.kts b/core/build.gradle.kts
new file mode 100644
index 0000000..b8710c4
--- /dev/null
+++ b/core/build.gradle.kts
@@ -0,0 +1,31 @@
+import org.jetbrains.kotlin.gradle.dsl.JvmTarget
+
+plugins {
+    alias(libs.plugins.kotlin.jvm)
+}
+
+// Plain JVM on purpose: no Android types in here, so the file format and the deinflector can be tested on a laptop.
+java {
+    sourceCompatibility = JavaVersion.VERSION_17
+    targetCompatibility = JavaVersion.VERSION_17
+}
+kotlin {
+    compilerOptions { jvmTarget.set(JvmTarget.JVM_17) }
+}
+
+dependencies {
+    implementation(libs.gson)
+
+    testImplementation(libs.junit)
+    // Property tests. It shrinks a failing input to the smallest one and prints the seed.
+    testImplementation(libs.kotest.property)
+    testImplementation(libs.kotlinx.coroutines.core)
+}
+
+tasks.test {
+    useJUnit()
+    testLogging {
+        events("failed")
+        exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
+    }
+}
diff --git a/core/src/main/kotlin/space/subread/dictionary/core/Deinflector.kt b/core/src/main/kotlin/space/subread/dictionary/core/Deinflector.kt
new file mode 100644
index 0000000..b3ac63d
--- /dev/null
+++ b/core/src/main/kotlin/space/subread/dictionary/core/Deinflector.kt
@@ -0,0 +1,283 @@
+package space.subread.dictionary.core
+
+/**
+ * A dictionary form that an inflected text can come from.
+ *
+ * @param text the dictionary form.
+ * @param conditions bit mask of the word classes that the last rule produced, from [Conditions].
+ *   Zero: the text is not deinflected, any term matches.
+ * @param reasons the names of the rules, from the text to the dictionary form.
+ */
+data class Deinflection(val text: String, val conditions: Int, val reasons: List<String>) {
+
+    /** True when a term with these rule identifiers (`v1`, `v5`, `vs`, `vk`, `vz`, `adj-i`) can be this form. */
+    fun accepts(termRules: String): Boolean {
+        if (conditions == 0) return true
+        return Conditions.maskOf(termRules) and conditions != 0
+    }
+}
+
+/** The word classes of the Japanese rules of Yomitan. Each leaf is one bit; a group is the bits of its leaves. */
+object Conditions {
+    private val leaves = listOf(
+        "v1d", "v1p", "v5d", "v5s", "v5ss", "v5sp", "vk", "vs", "vz", "adj-i",
+        "-ます", "-ません", "-て", "-ば", "-く", "-た", "-ん", "-なさい", "-ゃ",
+    )
+    private val bits: Map<String, Int> = buildMap {
+        leaves.forEachIndexed { i, name -> put(name, 1 shl i) }
+        put("v1", getValue("v1d") or getValue("v1p"))
+        put("v5", getValue("v5d") or getValue("v5s") or getValue("v5ss") or getValue("v5sp"))
+        put("v", getValue("v1") or getValue("v5") or getValue("vk") or getValue("vs") or getValue("vz"))
+    }
+
+    fun maskOf(names: Collection<String>): Int = names.fold(0) { acc, name -> acc or (bits[name] ?: 0) }
+
+    /** The mask of a space-separated rule string of a term. */
+    fun maskOf(rules: String): Int = maskOf(rules.split(' ').filter { it.isNotEmpty() })
+}
+
+/**
+ * Japanese deinflection, after the transforms of Yomitan. A rule takes a text that ends with
+ * `inflected`, in a word class of `conditionsIn`, and gives the text that ends with `base`, in a
+ * word class of `conditionsOut`. The rules chain: 食べさせられた → 食べさせられる → 食べさせる → 食べる.
+ */
+object Deinflector {
+
+    private class Rule(val reason: String, val inflected: String, val base: String, val conditionsIn: Int, val conditionsOut: Int)
+
+    private val rules = ArrayList<Rule>()
+
+    private fun rule(reason: String, inflected: String, base: String, conditionsIn: List<String>, conditionsOut: List<String>) {
+        rules.add(Rule(reason, inflected, base, Conditions.maskOf(conditionsIn), Conditions.maskOf(conditionsOut)))
+    }
+
+    /** The godan stems: the inflected ending, then the dictionary ending. */
+    private val godan = listOf("う" to "う", "く" to "く", "ぐ" to "ぐ", "す" to "す", "つ" to "つ", "ぬ" to "ぬ", "ぶ" to "ぶ", "む" to "む", "る" to "る")
+
+    /** Rules for a suffix that follows the i-stem (連用形): ます, たい, なさい, そう, すぎる, たり. */
+    private fun stemSuffix(reason: String, suffix: String, conditionsIn: List<String>, v5Out: String = "v5") {
+        val stems = listOf("い" to "う", "き" to "く", "ぎ" to "ぐ", "し" to "す", "ち" to "つ", "に" to "ぬ", "び" to "ぶ", "み" to "む", "り" to "る")
+        rule(reason, suffix, "る", conditionsIn, listOf("v1"))
+        for ((stem, end) in stems) rule(reason, stem + suffix, end, conditionsIn, listOf(v5Out))
+        rule(reason, "じ$suffix", "ずる", conditionsIn, listOf("vz"))
+        rule(reason, "し$suffix", "する", conditionsIn, listOf("vs"))
+        rule(reason, "為$suffix", "為る", conditionsIn, listOf("vs"))
+        rule(reason, "き$suffix", "くる", conditionsIn, listOf("vk"))
+        rule(reason, "来$suffix", "来る", conditionsIn, listOf("vk"))
+        rule(reason, "來$suffix", "來る", conditionsIn, listOf("vk"))
+    }
+
+    /** Rules for a suffix that follows the a-stem (未然形): ない, ず, ぬ, ん, せる, れる. */
+    private fun negativeStemSuffix(reason: String, suffix: String, conditionsIn: List<String>, v1Suffix: String = suffix) {
+        val stems = listOf("わ" to "う", "は" to "う", "か" to "く", "が" to "ぐ", "さ" to "す", "た" to "つ", "な" to "ぬ", "ば" to "ぶ", "ま" to "む", "ら" to "る")
+        rule(reason, v1Suffix, "る", conditionsIn, listOf("v1"))
+        for ((stem, end) in stems) rule(reason, stem + suffix, end, conditionsIn, listOf("v5"))
+        rule(reason, "じ$suffix", "ずる", conditionsIn, listOf("vz"))
+        rule(reason, "し$suffix", "する", conditionsIn, listOf("vs"))
+        rule(reason, "為$suffix", "為る", conditionsIn, listOf("vs"))
+        rule(reason, "こ$suffix", "くる", conditionsIn, listOf("vk"))
+        rule(reason, "来$suffix", "来る", conditionsIn, listOf("vk"))
+        rule(reason, "來$suffix", "來る", conditionsIn, listOf("vk"))
+    }
+
+    /** Rules for a suffix that follows the te/ta sound change (音便): て, た, たら, たり, ちゃう. */
+    private fun teSuffix(reason: String, te: String, conditionsIn: List<String>, vkOut: String = "vk") {
+        // The voiced form after ん and after the い of ぐ: 読んで, 泳いだ, 死んじゃう.
+        val de = when (te.first()) { 'て' -> "で"; 'た' -> "だ"; 'ち' -> "じ"; else -> te.take(1) } + te.drop(1)
+        rule(reason, te, "る", conditionsIn, listOf("v1"))
+        rule(reason, "い$te", "く", conditionsIn, listOf("v5"))
+        rule(reason, "い$de", "ぐ", conditionsIn, listOf("v5"))
+        rule(reason, "し$te", "す", conditionsIn, listOf("v5"))
+        rule(reason, "っ$te", "う", conditionsIn, listOf("v5"))
+        rule(reason, "っ$te", "つ", conditionsIn, listOf("v5"))
+        rule(reason, "っ$te", "る", conditionsIn, listOf("v5"))
+        // 行く, 往く, 逝く and いく sound like う-verbs in this form: 行った, not 行いた.
+        for (iku in listOf("行", "往", "逝", "い")) rule(reason, "${iku}っ$te", "${iku}く", conditionsIn, listOf("v5"))
+        rule(reason, "ん$de", "ぬ", conditionsIn, listOf("v5"))
+        rule(reason, "ん$de", "ぶ", conditionsIn, listOf("v5"))
+        rule(reason, "ん$de", "む", conditionsIn, listOf("v5"))
+        rule(reason, "じ$te", "ずる", conditionsIn, listOf("vz"))
+        rule(reason, "し$te", "する", conditionsIn, listOf("vs"))
+        rule(reason, "為$te", "為る", conditionsIn, listOf("vs"))
+        rule(reason, "き$te", "くる", conditionsIn, listOf(vkOut))
+        rule(reason, "来$te", "来る", conditionsIn, listOf(vkOut))
+        rule(reason, "來$te", "來る", conditionsIn, listOf(vkOut))
+    }
+
+    init {
+        // -ば
+        rule("-ば", "ければ", "い", listOf("-ば"), listOf("adj-i"))
+        for ((_, end) in godan) {
+            val e = when (end) { "う" -> "え"; "く" -> "け"; "ぐ" -> "げ"; "す" -> "せ"; "つ" -> "て"; "ぬ" -> "ね"; "ぶ" -> "べ"; "む" -> "め"; else -> "れ" }
+            rule("-ば", "${e}ば", end, listOf("-ば"), listOf("v5"))
+        }
+        rule("-ば", "へば", "う", listOf("-ば"), listOf("v5"))
+        rule("-ば", "れば", "る", listOf("-ば"), listOf("v1", "v5", "vk", "vs", "vz"))
+        rule("-ば", "れば", "", listOf("-ば"), listOf("-ます"))
+        // -ちゃう, -しまう
+        teSuffix("-ちゃう", "ちゃう", listOf("v5"))
+        rule("-しまう", "てしまう", "て", listOf("v5"), listOf("-て"))
+        rule("-しまう", "でしまう", "で", listOf("v5"), listOf("-て"))
+        // -なさい, -そう, -すぎる, -たい
+        stemSuffix("-なさい", "なさい", listOf("-なさい"))
+        stemSuffix("-そう", "そう", listOf())
+        rule("-そう", "そう", "い", listOf(), listOf("adj-i"))
+        stemSuffix("-すぎる", "すぎる", listOf("v1"))
+        rule("-すぎる", "すぎる", "い", listOf("v1"), listOf("adj-i"))
+        stemSuffix("-たい", "たい", listOf("adj-i"))
+        // -たら, -たり
+        rule("-たら", "かったら", "い", listOf(), listOf("adj-i"))
+        teSuffix("-たら", "たら", listOf())
+        rule("-たら", "ましたら", "ます", listOf(), listOf("-ます"))
+        rule("-たり", "かったり", "い", listOf(), listOf("adj-i"))
+        teSuffix("-たり", "たり", listOf())
+        rule("-たり", "ましたり", "ます", listOf(), listOf("-ます"))
+        // -ず, -ぬ, -ん (negative)
+        negativeStemSuffix("-ず", "ず", listOf())
+        negativeStemSuffix("-ぬ", "ぬ", listOf())
+        negativeStemSuffix("-ん", "ん", listOf("-ん"))
+        rule("-ん", "ません", "ます", listOf("-ん"), listOf("-ます"))
+        // adverb, -さ
+        rule("adv", "く", "い", listOf("-く"), listOf("adj-i"))
+        rule("-さ", "さ", "い", listOf(), listOf("adj-i"))
+        // causative
+        negativeStemSuffix("causative", "せる", listOf("v1"), v1Suffix = "させる")
+        rule("causative", "させる", "する", listOf("v1"), listOf("vs"))
+        rule("causative", "為せる", "為る", listOf("v1"), listOf("vs"))
+        rule("causative", "こさせる", "くる", listOf("v1"), listOf("vk"))
+        rule("causative", "来させる", "来る", listOf("v1"), listOf("vk"))
+        rule("causative", "來させる", "來る", listOf("v1"), listOf("vk"))
+        // imperative
+        rule("imperative", "ろ", "る", listOf(), listOf("v1"))
+        rule("imperative", "よ", "る", listOf(), listOf("v1"))
+        for ((_, end) in godan) {
+            val e = when (end) { "う" -> "え"; "く" -> "け"; "ぐ" -> "げ"; "す" -> "せ"; "つ" -> "て"; "ぬ" -> "ね"; "ぶ" -> "べ"; "む" -> "め"; else -> "れ" }
+            rule("imperative", e, end, listOf(), listOf("v5"))
+        }
+        rule("imperative", "へ", "う", listOf(), listOf("v5"))
+        rule("imperative", "じろ", "ずる", listOf(), listOf("vz"))
+        rule("imperative", "ぜよ", "ずる", listOf(), listOf("vz"))
+        rule("imperative", "しろ", "する", listOf(), listOf("vs"))
+        rule("imperative", "せよ", "する", listOf(), listOf("vs"))
+        rule("imperative", "為ろ", "為る", listOf(), listOf("vs"))
+        rule("imperative", "為よ", "為る", listOf(), listOf("vs"))
+        rule("imperative", "こい", "くる", listOf(), listOf("vk"))
+        rule("imperative", "来い", "来る", listOf(), listOf("vk"))
+        rule("imperative", "來い", "來る", listOf(), listOf("vk"))
+        // continuative (連用形) as a word on its own
+        for (stem in listOf("い", "え", "き", "ぎ", "け", "げ", "じ", "せ", "ぜ", "ち", "て", "で", "に", "ね", "ひ", "び", "へ", "べ", "み", "め", "り", "れ")) {
+            rule("continuative", stem, "${stem}る", listOf(), listOf("v1d"))
+        }
+        for ((stem, end) in listOf("い" to "う", "ひ" to "う", "き" to "く", "ぎ" to "ぐ", "し" to "す", "ち" to "つ", "に" to "ぬ", "び" to "ぶ", "み" to "む", "り" to "る")) {
+            rule("continuative", stem, end, listOf(), listOf("v5"))
+        }
+        rule("continuative", "き", "くる", listOf(), listOf("vk"))
+        rule("continuative", "し", "する", listOf(), listOf("vs"))
+        rule("continuative", "来", "来る", listOf(), listOf("vk"))
+        rule("continuative", "來", "來る", listOf(), listOf("vk"))
+        // negative
+        rule("negative", "くない", "い", listOf("adj-i"), listOf("adj-i"))
+        negativeStemSuffix("negative", "ない", listOf("adj-i"))
+        rule("negative", "ません", "ます", listOf("-ません"), listOf("-ます"))
+        // passive
+        negativeStemSuffix("passive", "れる", listOf("v1"), v1Suffix = "られる")
+        rule("passive", "される", "する", listOf("v1"), listOf("vs"))
+        rule("passive", "為れる", "為る", listOf("v1"), listOf("vs"))
+        rule("passive", "こられる", "くる", listOf("v1"), listOf("vk"))
+        rule("passive", "来られる", "来る", listOf("v1"), listOf("vk"))
+        rule("passive", "來られる", "來る", listOf("v1"), listOf("vk"))
+        // past
+        rule("past", "かった", "い", listOf("-た"), listOf("adj-i"))
+        teSuffix("past", "た", listOf("-た"))
+        rule("past", "ました", "ます", listOf("-た"), listOf("-ます"))
+        rule("past", "でした", "", listOf("-た"), listOf("-ません"))
+        rule("past", "かった", "", listOf("-た"), listOf("-ません", "-ん"))
+        // polite
+        stemSuffix("polite", "ます", listOf("-ます"), v5Out = "v5d")
+        rule("polite", "ひます", "う", listOf("-ます"), listOf("v5d"))
+        rule("polite", "くあります", "い", listOf("-ます"), listOf("adj-i"))
+        // potential
+        rule("potential", "れる", "る", listOf("v1"), listOf("v1", "v5d"))
+        for ((_, end) in godan) {
+            if (end == "る") continue
+            val e = when (end) { "う" -> "え"; "く" -> "け"; "ぐ" -> "げ"; "す" -> "せ"; "つ" -> "て"; "ぬ" -> "ね"; "ぶ" -> "べ"; else -> "め" }
+            rule("potential", "${e}る", end, listOf("v1"), listOf("v5d"))
+        }
+        rule("potential", "できる", "する", listOf("v1"), listOf("vs"))
+        rule("potential", "出来る", "する", listOf("v1"), listOf("vs"))
+        rule("potential", "これる", "くる", listOf("v1"), listOf("vk"))
+        rule("potential", "来れる", "来る", listOf("v1"), listOf("vk"))
+        rule("potential", "來れる", "來る", listOf("v1"), listOf("vk"))
+        // potential or passive
+        rule("potential or passive", "られる", "る", listOf("v1"), listOf("v1"))
+        // volitional
+        rule("volitional", "よう", "る", listOf(), listOf("v1"))
+        rule("volitional", "やう", "る", listOf(), listOf("v1"))
+        for ((_, end) in godan) {
+            val o = when (end) { "う" -> "お"; "く" -> "こ"; "ぐ" -> "ご"; "す" -> "そ"; "つ" -> "と"; "ぬ" -> "の"; "ぶ" -> "ぼ"; "む" -> "も"; else -> "ろ" }
+            val a = when (end) { "う" -> "は"; "く" -> "か"; "ぐ" -> "が"; "す" -> "さ"; "つ" -> "た"; "ぬ" -> "な"; "ぶ" -> "ば"; "む" -> "ま"; else -> "ら" }
+            rule("volitional", "${o}う", end, listOf(), listOf("v5"))
+            rule("volitional", "${a}う", end, listOf(), listOf("v5"))
+        }
+        rule("volitional", "じよう", "ずる", listOf(), listOf("vz"))
+        rule("volitional", "しよう", "する", listOf(), listOf("vs"))
+        rule("volitional", "為よう", "為る", listOf(), listOf("vs"))
+        rule("volitional", "こよう", "くる", listOf(), listOf("vk"))
+        rule("volitional", "来よう", "来る", listOf(), listOf("vk"))
+        rule("volitional", "來よう", "來る", listOf(), listOf("vk"))
+        rule("volitional", "ましょう", "ます", listOf(), listOf("-ます"))
+        rule("volitional", "かろう", "い", listOf(), listOf("adj-i"))
+        // -て
+        rule("-て", "くて", "い", listOf("-て"), listOf("adj-i"))
+        teSuffix("-て", "て", listOf("-て"))
+        rule("-て", "まして", "ます", listOf(), listOf("-ます"))
+        // -ている, -ておく, -ていく, -てくる
+        rule("-ている", "ている", "て", listOf("v1"), listOf("-て"))
+        rule("-ている", "てゐる", "て", listOf("v1"), listOf("-て"))
+        rule("-ている", "ておる", "て", listOf("v5"), listOf("-て"))
+        rule("-ている", "てる", "て", listOf("v1p"), listOf("-て"))
+        rule("-ている", "でいる", "で", listOf("v1"), listOf("-て"))
+        rule("-ている", "でゐる", "で", listOf("v1"), listOf("-て"))
+        rule("-ている", "でおる", "で", listOf("v5"), listOf("-て"))
+        rule("-ている", "でる", "で", listOf("v1p"), listOf("-て"))
+        rule("-ている", "とる", "て", listOf("v5"), listOf("-て"))
+        rule("-ている", "ないでいる", "ない", listOf("v1"), listOf("adj-i"))
+        rule("-ておく", "ておく", "て", listOf("v5"), listOf("-て"))
+        rule("-ておく", "でおく", "で", listOf("v5"), listOf("-て"))
+        rule("-ておく", "とく", "て", listOf("v5"), listOf("-て"))
+        rule("-ておく", "どく", "で", listOf("v5"), listOf("-て"))
+        rule("-ておく", "ないでおく", "ない", listOf("v5"), listOf("adj-i"))
+        rule("-ていく", "ていく", "て", listOf("v5"), listOf("-て"))
+        rule("-ていく", "でいく", "で", listOf("v5"), listOf("-て"))
+        rule("-てくる", "てくる", "て", listOf("vk"), listOf("-て"))
+        rule("-てくる", "でくる", "で", listOf("vk"), listOf("-て"))
+    }
+
+    /** The maximum number of forms tried for one text. A text of normal length is far below it. */
+    private const val LIMIT = 2000
+
+    /**
+     * Each dictionary form that the text can come from. The first result is the text itself, with
+     * no conditions. The others come in breadth-first order: the fewest rules first.
+     */
+    fun deinflect(text: String): List<Deinflection> {
+        if (text.isEmpty()) return emptyList()
+        val results = ArrayList<Deinflection>()
+        val seen = HashSet<Pair<String, Int>>()
+        results.add(Deinflection(text, 0, emptyList()))
+        seen.add(text to 0)
+        var i = 0
+        while (i < results.size && results.size < LIMIT) {
+            val current = results[i++]
+            for (rule in rules) {
+                if (rule.conditionsIn != 0 && current.conditions != 0 && rule.conditionsIn and current.conditions == 0) continue
+                if (!current.text.endsWith(rule.inflected)) continue
+                val base = current.text.dropLast(rule.inflected.length) + rule.base
+                if (base.isEmpty()) continue
+                if (!seen.add(base to rule.conditionsOut)) continue
+                results.add(Deinflection(base, rule.conditionsOut, current.reasons + rule.reason))
+            }
+        }
+        return results
+    }
+}
diff --git a/core/src/main/kotlin/space/subread/dictionary/core/Glossary.kt b/core/src/main/kotlin/space/subread/dictionary/core/Glossary.kt
new file mode 100644
index 0000000..2eebc6a
--- /dev/null
+++ b/core/src/main/kotlin/space/subread/dictionary/core/Glossary.kt
@@ -0,0 +1,142 @@
+package space.subread.dictionary.core
+
+import com.google.gson.JsonArray
+import com.google.gson.JsonElement
+import com.google.gson.JsonObject
+import com.google.gson.JsonParser
+
+/**
+ * Turns the glossary of a term, and the meta of a term, into simple HTML: `b`, `i`, `u`, `br`,
+ * `ul`, `li`, `a`. A phone shows it with `Html.fromHtml`, which knows these tags and no table.
+ */
+object Glossary {
+
+    /** The glossary array of a term as HTML. Each definition is one line. */
+    fun toHtml(glossaryJson: String): String {
+        val array = runCatching { JsonParser.parseString(glossaryJson) }.getOrNull()
+        if (array == null || !array.isJsonArray) return escape(glossaryJson)
+        val lines = array.asJsonArray.map { definition(it).trim() }.filter { it.isNotEmpty() }
+        return lines.joinToString("<br>")
+    }
+
+    /** The glossary as plain text, one definition per line. For a search result list, or a test. */
+    fun toText(glossaryJson: String): String = toHtml(glossaryJson)
+        .replace("<br>", "\n")
+        .replace(Regex("<[^>]+>"), "")
+        .let(::unescape)
+
+    private fun definition(element: JsonElement): String = when {
+        element.isJsonPrimitive -> escape(element.asString)
+        element.isJsonArray -> element.asJsonArray.joinToString("") { definition(it) }
+        element.isJsonObject -> {
+            val obj = element.asJsonObject
+            when (obj.get("type")?.asString) {
+                "text" -> escape(obj.get("text")?.asString ?: "")
+                "image" -> image(obj)
+                "structured-content" -> node(obj.get("content"))
+                else -> node(element)
+            }
+        }
+        else -> ""
+    }
+
+    /** A node of structured content: a string, an array of nodes, or an element with a tag. */
+    private fun node(element: JsonElement?): String {
+        if (element == null || element.isJsonNull) return ""
+        if (element.isJsonPrimitive) return escape(element.asString)
+        if (element.isJsonArray) return element.asJsonArray.joinToString("") { node(it) }
+        val obj = element.asJsonObject
+        val tag = obj.get("tag")?.asString ?: return ""
+        val inner = node(obj.get("content"))
+        return when (tag) {
+            "br" -> "<br>"
+            "img" -> image(obj)
+            "a" -> {
+                val href = obj.get("href")?.asString
+                if (href != null && href.startsWith("http")) "<a href=\"${escape(href)}\">$inner</a>" else inner
+            }
+            "ruby" -> inner
+            "rt" -> "<small>($inner)</small>"
+            "rp" -> ""
+            "ol", "ul" -> "<ul>$inner</ul>"
+            "li" -> "<li>${styled(obj, inner)}</li>"
+            "table", "thead", "tbody", "tfoot" -> inner
+            "tr" -> "$inner<br>"
+            "td", "th" -> "$inner&nbsp;| "
+            "div", "details", "summary" -> block(styled(obj, inner))
+            else -> styled(obj, inner)
+        }
+    }
+
+    /** A block starts on its own line. Two blocks in a row keep one line break between them. */
+    private fun block(inner: String): String =
+        if (inner.isEmpty()) "" else if (inner.endsWith("<br>")) inner else "$inner<br>"
+
+    private fun styled(obj: JsonObject, inner: String): String {
+        val style = obj.get("style")?.takeIf { it.isJsonObject }?.asJsonObject ?: return inner
+        var out = inner
+        if (style.get("fontWeight")?.asString?.let { it == "bold" || (it.toIntOrNull() ?: 0) >= 600 } == true) out = "<b>$out</b>"
+        if (style.get("fontStyle")?.asString == "italic") out = "<i>$out</i>"
+        if (style.get("textDecorationLine")?.let { it.toString().contains("underline") } == true) out = "<u>$out</u>"
+        if (style.get("verticalAlign")?.asString == "super") out = "<sup>$out</sup>"
+        if (style.get("verticalAlign")?.asString == "sub") out = "<sub>$out</sub>"
+        return out
+    }
+
+    /** The app has no image store. The alt text, or the file name, stands in for the picture. */
+    private fun image(obj: JsonObject): String {
+        val alt = obj.get("alt")?.asString ?: obj.get("title")?.asString ?: obj.get("path")?.asString?.substringAfterLast('/') ?: ""
+        return "<i>[${escape(alt)}]</i>"
+    }
+
+    /** Frequency meta as short text: the display value when there is one, else the rank. */
+    fun frequencyText(dataJson: String): String {
+        val data = runCatching { JsonParser.parseString(dataJson) }.getOrNull() ?: return ""
+        return frequency(data)
+    }
+
+    private fun frequency(data: JsonElement): String = when {
+        data.isJsonPrimitive -> data.asString
+        data.isJsonObject -> {
+            val obj = data.asJsonObject
+            when {
+                obj.has("frequency") -> frequency(obj.get("frequency"))
+                obj.has("displayValue") -> obj.get("displayValue").asString
+                obj.has("value") -> obj.get("value").asString
+                else -> ""
+            }
+        }
+        else -> ""
+    }
+
+    /** The reading that a frequency entry is for, or null when it is for every reading. */
+    fun frequencyReading(dataJson: String): String? {
+        val data = runCatching { JsonParser.parseString(dataJson) }.getOrNull() ?: return null
+        return data.takeIf { it.isJsonObject }?.asJsonObject?.get("reading")?.asString
+    }
+
+    /** Pitch meta as text: the reading and the accent positions, `はし [2]`. */
+    fun pitchText(dataJson: String): String {
+        val obj = runCatching { JsonParser.parseString(dataJson) }.getOrNull()?.takeIf { it.isJsonObject }?.asJsonObject ?: return ""
+        val reading = obj.get("reading")?.asString ?: ""
+        val pitches = obj.get("pitches")?.takeIf { it.isJsonArray }?.asJsonArray ?: JsonArray()
+        val positions = pitches.mapNotNull { it.asJsonObject.get("position")?.asString }
+        return if (positions.isEmpty()) reading else "$reading [${positions.joinToString(", ")}]"
+    }
+
+    fun pitchReading(dataJson: String): String? =
+        runCatching { JsonParser.parseString(dataJson) }.getOrNull()?.takeIf { it.isJsonObject }?.asJsonObject?.get("reading")?.asString
+
+    fun escape(text: String): String = buildString(text.length) {
+        for (c in text) when (c) {
+            '&' -> append("&amp;")
+            '<' -> append("&lt;")
+            '>' -> append("&gt;")
+            '"' -> append("&quot;")
+            else -> append(c)
+        }
+    }
+
+    private fun unescape(text: String): String =
+        text.replace("&nbsp;", " ").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&amp;", "&")
+}
diff --git a/core/src/main/kotlin/space/subread/dictionary/core/Kana.kt b/core/src/main/kotlin/space/subread/dictionary/core/Kana.kt
new file mode 100644
index 0000000..50bc75d
--- /dev/null
+++ b/core/src/main/kotlin/space/subread/dictionary/core/Kana.kt
@@ -0,0 +1,18 @@
+package space.subread.dictionary.core
+
+/** Kana helpers. A dictionary has readings in hiragana; a text can have the same word in katakana. */
+object Kana {
+
+    fun isHiragana(c: Char) = c in 'ぁ'..'ゖ' || c == 'ゝ' || c == 'ゞ'
+
+    fun isKatakana(c: Char) = c in 'ァ'..'ヶ' || c == 'ヽ' || c == 'ヾ'
+
+    fun isKana(c: Char) = isHiragana(c) || isKatakana(c) || c == 'ー'
+
+    fun isJapanese(c: Char) = isKana(c) || c in '一'..'鿿' || c in '㐀'..'䶿' || c == '々' || c == '〆'
+
+    /** Katakana to hiragana. Other characters stay. */
+    fun toHiragana(text: String): String = buildString(text.length) {
+        for (c in text) append(if (isKatakana(c)) (c.code - 0x60).toChar() else c)
+    }
+}
diff --git a/core/src/main/kotlin/space/subread/dictionary/core/Lookup.kt b/core/src/main/kotlin/space/subread/dictionary/core/Lookup.kt
new file mode 100644
index 0000000..4c5135f
--- /dev/null
+++ b/core/src/main/kotlin/space/subread/dictionary/core/Lookup.kt
@@ -0,0 +1,70 @@
+package space.subread.dictionary.core
+
+/** A term with the dictionary it comes from. The dictionary position is the order the user chose. */
+data class StoredTerm(val dictionaryId: Long, val dictionaryTitle: String, val dictionaryPosition: Int, val term: Term)
+
+/** Where the terms are: on a phone, a SQLite table. In a test, a list. */
+interface TermSource {
+    /** Each term whose expression, or whose reading, is one of the texts. */
+    fun terms(texts: Collection<String>): List<StoredTerm>
+}
+
+/**
+ * One term that matches the text.
+ *
+ * @param length how many characters of the text, from the scan position, the term covers.
+ * @param reasons the deinflection, from the text to the dictionary form. Empty when the text is the dictionary form.
+ */
+data class Match(val stored: StoredTerm, val length: Int, val reasons: List<String>)
+
+/** Looks a text up: the longest term at the scan position first, like the Yomitan popup. */
+object Lookup {
+
+    /** The most characters a term can cover. Longer terms are rare, and each character costs a scan. */
+    const val MAX_LENGTH = 24
+
+    /**
+     * Each term that starts at `offset` in `text`, longest first. Within one length, the
+     * dictionaries in their order, and within one dictionary the higher score first.
+     */
+    fun find(text: String, offset: Int, source: TermSource): List<Match> {
+        val end = minOf(text.length, offset + MAX_LENGTH)
+        if (offset < 0 || offset >= end) return emptyList()
+
+        // Every dictionary form for every prefix, then one query for all of them.
+        data class Candidate(val form: Deinflection, val length: Int)
+        val candidates = ArrayList<Candidate>()
+        for (stop in end downTo offset + 1) {
+            val slice = text.substring(offset, stop)
+            val variants = linkedSetOf(slice, Kana.toHiragana(slice))
+            for (variant in variants) {
+                for (form in Deinflector.deinflect(variant)) candidates.add(Candidate(form, stop - offset))
+            }
+        }
+        val byText = candidates.groupBy { it.form.text }
+        val found = source.terms(byText.keys)
+
+        val matches = ArrayList<Match>()
+        // One match per term: the longest one, because the candidates come longest first.
+        // 食べる is both the text itself and the continuative 食べ plus る; the text itself wins.
+        val seen = HashSet<Pair<Long, Term>>()
+        for (stored in found) {
+            val term = stored.term
+            // A kana text matches the reading; a text with kanji matches the expression.
+            val forms = (byText[term.expression].orEmpty() +
+                (if (term.reading.isNotEmpty() && term.reading != term.expression) byText[term.reading].orEmpty() else emptyList()))
+                .sortedByDescending { it.length }
+            for (candidate in forms) {
+                if (!candidate.form.accepts(term.rules)) continue
+                if (!seen.add(stored.dictionaryId to term)) continue
+                matches.add(Match(stored, candidate.length, candidate.form.reasons))
+            }
+        }
+        return matches.sortedWith(
+            compareByDescending<Match> { it.length }
+                .thenBy { it.reasons.size }
+                .thenBy { it.stored.dictionaryPosition }
+                .thenByDescending { it.stored.term.score },
+        )
+    }
+}
diff --git a/core/src/main/kotlin/space/subread/dictionary/core/Yomitan.kt b/core/src/main/kotlin/space/subread/dictionary/core/Yomitan.kt
new file mode 100644
index 0000000..7a76651
--- /dev/null
+++ b/core/src/main/kotlin/space/subread/dictionary/core/Yomitan.kt
@@ -0,0 +1,171 @@
+package space.subread.dictionary.core
+
+import com.google.gson.JsonParser
+import com.google.gson.stream.JsonReader
+import com.google.gson.stream.JsonToken
+import java.io.InputStream
+import java.io.InputStreamReader
+import java.util.zip.ZipInputStream
+
+/** The `index.json` of a Yomitan dictionary. */
+data class DictionaryIndex(
+    val title: String,
+    val revision: String,
+    /** 1, 2 or 3. This app reads format 3 only: the term banks of the other formats have other fields. */
+    val format: Int,
+    val sequenced: Boolean = false,
+)
+
+/** One row of a `term_bank_N.json` file, format 3. */
+data class Term(
+    val expression: String,
+    /** Empty when the reading is the expression. */
+    val reading: String,
+    /** Space-separated tags of the definition. */
+    val definitionTags: String,
+    /** Space-separated rule identifiers (`v1`, `v5`, `vs`, `vk`, `adj-i`). The deinflector checks a match against them. */
+    val rules: String,
+    val score: Double,
+    /** The glossary as JSON text: an array of strings and structured content. `Glossary` renders it. */
+    val glossary: String,
+    val sequence: Long,
+    /** Space-separated tags of the term. */
+    val termTags: String,
+)
+
+/** One row of a `term_meta_bank_N.json` file: frequency, pitch accent or IPA of a term. */
+data class TermMeta(
+    val expression: String,
+    /** `freq`, `pitch` or `ipa`. */
+    val mode: String,
+    /** The data as JSON text. `Glossary` renders it. */
+    val data: String,
+)
+
+/** One row of a `tag_bank_N.json` file. */
+data class Tag(
+    val name: String,
+    val category: String,
+    val order: Int,
+    val notes: String,
+    val score: Double,
+)
+
+/** Takes the rows of a dictionary as the reader finds them. */
+interface DictionarySink {
+    fun term(term: Term)
+    fun termMeta(meta: TermMeta)
+    fun tag(tag: Tag)
+}
+
+/**
+ * Reads a Yomitan dictionary zip. The JSON files are in the root of the zip. Each file is read as
+ * a stream, so a term bank of many megabytes takes little memory.
+ */
+object YomitanZip {
+
+    /** The index alone. The zip can have the index after the term banks, so the caller opens the zip twice. */
+    fun readIndex(zip: InputStream): DictionaryIndex {
+        ZipInputStream(zip).use { stream ->
+            while (true) {
+                val entry = stream.nextEntry ?: break
+                if (entry.name == "index.json") return parseIndex(stream.readBytes().decodeToString())
+            }
+        }
+        throw DictionaryFormatException("No index.json in the zip.")
+    }
+
+    fun parseIndex(json: String): DictionaryIndex {
+        val root = JsonParser.parseString(json).asJsonObject
+        val format = root.get("format")?.asInt ?: root.get("version")?.asInt
+            ?: throw DictionaryFormatException("index.json has no format or version.")
+        return DictionaryIndex(
+            title = root.get("title")?.asString ?: throw DictionaryFormatException("index.json has no title."),
+            revision = root.get("revision")?.asString ?: "",
+            format = format,
+            sequenced = root.get("sequenced")?.asBoolean ?: false,
+        )
+    }
+
+    /** Reads the term, term meta and tag banks. Kanji banks are skipped. */
+    fun readBanks(zip: InputStream, sink: DictionarySink) {
+        ZipInputStream(zip).use { stream ->
+            while (true) {
+                val entry = stream.nextEntry ?: break
+                val name = entry.name.substringAfterLast('/')
+                val reader = JsonReader(InputStreamReader(stream, Charsets.UTF_8))
+                when {
+                    name.startsWith("term_meta_bank_") -> readTermMetaBank(reader, sink)
+                    name.startsWith("term_bank_") -> readTermBank(reader, sink)
+                    name.startsWith("tag_bank_") -> readTagBank(reader, sink)
+                }
+            }
+        }
+    }
+
+    fun readTermBank(reader: JsonReader, sink: DictionarySink) {
+        reader.beginArray()
+        while (reader.hasNext()) {
+            reader.beginArray()
+            val term = Term(
+                expression = reader.nextString(),
+                reading = reader.nextString(),
+                definitionTags = reader.nextStringOrNull() ?: "",
+                rules = reader.nextString(),
+                score = reader.nextDouble(),
+                glossary = JsonParser.parseReader(reader).toString(),
+                sequence = reader.nextDouble().toLong(),
+                termTags = reader.nextString(),
+            )
+            // A dictionary of another format has more fields, or fewer. Skip what is left of the row.
+            while (reader.hasNext()) reader.skipValue()
+            reader.endArray()
+            sink.term(term)
+        }
+        reader.endArray()
+    }
+
+    fun readTermMetaBank(reader: JsonReader, sink: DictionarySink) {
+        reader.beginArray()
+        while (reader.hasNext()) {
+            reader.beginArray()
+            val meta = TermMeta(
+                expression = reader.nextString(),
+                mode = reader.nextString(),
+                data = JsonParser.parseReader(reader).toString(),
+            )
+            while (reader.hasNext()) reader.skipValue()
+            reader.endArray()
+            sink.termMeta(meta)
+        }
+        reader.endArray()
+    }
+
+    fun readTagBank(reader: JsonReader, sink: DictionarySink) {
+        reader.beginArray()
+        while (reader.hasNext()) {
+            reader.beginArray()
+            val tag = Tag(
+                name = reader.nextString(),
+                category = reader.nextString(),
+                order = reader.nextDouble().toInt(),
+                notes = reader.nextString(),
+                score = reader.nextDouble(),
+            )
+            while (reader.hasNext()) reader.skipValue()
+            reader.endArray()
+            sink.tag(tag)
+        }
+        reader.endArray()
+    }
+
+    private fun JsonReader.nextStringOrNull(): String? =
+        if (peek() == JsonToken.NULL) {
+            nextNull()
+            null
+        } else {
+            nextString()
+        }
+}
+
+class DictionaryFormatException(message: String) : Exception(message)
diff --git a/core/src/test/kotlin/space/subread/dictionary/core/CoreTest.kt b/core/src/test/kotlin/space/subread/dictionary/core/CoreTest.kt
new file mode 100644
index 0000000..97b6ba5
--- /dev/null
+++ b/core/src/test/kotlin/space/subread/dictionary/core/CoreTest.kt
@@ -0,0 +1,293 @@
+package space.subread.dictionary.core
+
+import com.google.gson.JsonArray
+import com.google.gson.JsonPrimitive
+import io.kotest.property.Arb
+import io.kotest.property.arbitrary.double
+import io.kotest.property.arbitrary.int
+import io.kotest.property.arbitrary.list
+import io.kotest.property.arbitrary.long
+import io.kotest.property.arbitrary.map
+import io.kotest.property.arbitrary.orNull
+import io.kotest.property.arbitrary.string
+import io.kotest.property.arbitrary.stringPattern
+import io.kotest.property.checkAll
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+import java.util.zip.ZipEntry
+import java.util.zip.ZipOutputStream
+
+class DeinflectorTest {
+
+    private fun forms(text: String) = Deinflector.deinflect(text).map { it.text }.toSet()
+
+    private fun accepted(text: String, base: String, rules: String) =
+        Deinflector.deinflect(text).any { it.text == base && it.accepts(rules) }
+
+    @Test
+    fun theTextItselfComesFirst() {
+        val first = Deinflector.deinflect("食べた").first()
+        assertEquals("食べた", first.text)
+        assertEquals(0, first.conditions)
+        assertTrue(first.accepts(""))
+        assertTrue(first.accepts("v5"))
+    }
+
+    @Test
+    fun commonVerbForms() {
+        assertTrue(accepted("食べた", "食べる", "v1"))
+        assertTrue(accepted("食べなかった", "食べる", "v1"))
+        assertTrue(accepted("食べさせられた", "食べる", "v1"))
+        assertTrue(accepted("食べています", "食べる", "v1"))
+        assertTrue(accepted("食べてる", "食べる", "v1"))
+        assertTrue(accepted("書いて", "書く", "v5"))
+        assertTrue(accepted("行った", "行く", "v5"))
+        assertTrue(accepted("泳いだ", "泳ぐ", "v5"))
+        assertTrue(accepted("読んで", "読む", "v5"))
+        assertTrue(accepted("飲まれた", "飲む", "v5"))
+        assertTrue(accepted("話せば", "話す", "v5"))
+        assertTrue(accepted("待ちます", "待つ", "v5"))
+        assertTrue(accepted("死んじゃった", "死ぬ", "v5"))
+        assertTrue(accepted("来なかった", "来る", "vk"))
+        assertTrue(accepted("しました", "する", "vs"))
+        assertTrue(accepted("できる", "する", "vs"))
+        assertTrue(accepted("勉強しよう", "勉強する", "vs"))
+        assertTrue(accepted("知らず", "知る", "v5"))
+        assertTrue(accepted("わからん", "わかる", "v5"))
+        assertTrue(accepted("見とく", "見る", "v1"))
+    }
+
+    @Test
+    fun adjectiveForms() {
+        assertTrue(accepted("高くなかった", "高い", "adj-i"))
+        assertTrue(accepted("高くて", "高い", "adj-i"))
+        assertTrue(accepted("高ければ", "高い", "adj-i"))
+        assertTrue(accepted("高そう", "高い", "adj-i"))
+        assertTrue(accepted("高さ", "高い", "adj-i"))
+        assertTrue(accepted("早く", "早い", "adj-i"))
+    }
+
+    @Test
+    fun theWordClassIsChecked() {
+        // 食べた is not the past of a godan verb that ends in た.
+        assertTrue(!accepted("食べた", "食べる", "v5"))
+        // A noun has no rules, so it matches the text itself only.
+        assertTrue(!accepted("本た", "本", ""))
+        assertTrue(accepted("本", "本", ""))
+    }
+
+    @Test
+    fun eachRuleChainGivesAShorterOrEqualOrTheSameKindOfText(): Unit = runBlocking {
+        // The deinflector ends for every text and never returns an empty form.
+        checkAll(Arb.stringPattern("[あ-んア-ン一-十]{0,12}")) { text ->
+            val all = Deinflector.deinflect(text)
+            assertTrue(all.size < 2000)
+            assertTrue(all.all { it.text.isNotEmpty() })
+            assertEquals(all.size, all.map { it.text to it.conditions }.toSet().size)
+        }
+    }
+
+    @Test
+    fun noneOfTheRuleChainsLoop() {
+        for (text in listOf("いる", "い", "きる", "し", "する", "くる", "た", "て", "ない", "ます", "れる", "られる", "せる")) {
+            forms(text)
+        }
+    }
+}
+
+class KanaTest {
+    @Test
+    fun katakanaBecomesHiragana() {
+        assertEquals("ぱん", Kana.toHiragana("パン"))
+        assertEquals("コーヒー".let { "こーひー" }, Kana.toHiragana("コーヒー"))
+        assertEquals("漢字abc", Kana.toHiragana("漢字abc"))
+    }
+}
+
+class GlossaryTest {
+    @Test
+    fun plainStringsAreLines() {
+        assertEquals("to eat<br>to live on", Glossary.toHtml("""["to eat","to live on"]"""))
+        assertEquals("to eat\nto live on", Glossary.toText("""["to eat","to live on"]"""))
+    }
+
+    @Test
+    fun structuredContentKeepsTheTextAndSimpleTags() {
+        val json = """[{"type":"structured-content","content":[
+            {"tag":"div","content":[{"tag":"span","style":{"fontWeight":"bold"},"content":"1."}," to eat"]},
+            {"tag":"ul","content":[{"tag":"li","content":"first"},{"tag":"li","content":"second"}]},
+            {"tag":"ruby","content":["食",{"tag":"rt","content":"た"}]},
+            {"tag":"img","path":"img/x.png","alt":"picture"},
+            {"tag":"a","href":"https://example.com","content":"link"},
+            {"tag":"table","content":[{"tag":"tr","content":[{"tag":"td","content":"a"},{"tag":"td","content":"b"}]}]}
+        ]}]"""
+        val html = Glossary.toHtml(json)
+        assertTrue(html, html.contains("<b>1.</b> to eat<br>"))
+        assertTrue(html, html.contains("<ul><li>first</li><li>second</li></ul>"))
+        assertTrue(html, html.contains("食<small>(た)</small>"))
+        assertTrue(html, html.contains("<i>[picture]</i>"))
+        assertTrue(html, html.contains("<a href=\"https://example.com\">link</a>"))
+        assertTrue(html, html.contains("a&nbsp;| b&nbsp;| <br>"))
+    }
+
+    @Test
+    fun textIsEscaped() {
+        assertEquals("a &lt;b&gt; &amp; c", Glossary.toHtml("""["a <b> & c"]"""))
+        assertEquals("a <b> & c", Glossary.toText("""["a <b> & c"]"""))
+    }
+
+    @Test
+    fun meta() {
+        assertEquals("12", Glossary.frequencyText("12"))
+        assertEquals("12㋕", Glossary.frequencyText("""{"value":12,"displayValue":"12㋕"}"""))
+        assertEquals("3", Glossary.frequencyText("""{"reading":"はし","frequency":{"value":3}}"""))
+        assertEquals("はし", Glossary.frequencyReading("""{"reading":"はし","frequency":3}"""))
+        assertEquals("はし [2, 0]", Glossary.pitchText("""{"reading":"はし","pitches":[{"position":2},{"position":0}]}"""))
+    }
+}
+
+class YomitanZipTest {
+
+    private val arbTerm = Arb.list(
+        Arb.stringPattern("[ぁ-ん一-十a-z]{1,6}"),
+        1..40,
+    ).map { words ->
+        words.mapIndexed { i, word ->
+            Term(
+                expression = word,
+                reading = if (i % 2 == 0) "" else "よみ$i",
+                definitionTags = if (i % 3 == 0) "" else "n vs",
+                rules = if (i % 4 == 0) "v1" else "",
+                score = (i * 7 % 11).toDouble(),
+                glossary = JsonArray().apply { add(JsonPrimitive("gloss $i \"quoted\" <b>")); add(JsonPrimitive("second")) }.toString(),
+                sequence = i.toLong() * 100,
+                termTags = "P",
+            )
+        }
+    }
+
+    private fun zip(index: String, terms: List<Term>, metas: List<TermMeta>, tags: List<Tag>): ByteArray {
+        val bytes = ByteArrayOutputStream()
+        ZipOutputStream(bytes).use { out ->
+            fun file(name: String, body: String) {
+                out.putNextEntry(ZipEntry(name))
+                out.write(body.toByteArray())
+                out.closeEntry()
+            }
+            file("term_bank_1.json", JsonArray().apply {
+                for (t in terms) add(JsonArray().apply {
+                    add(t.expression); add(t.reading)
+                    if (t.definitionTags.isEmpty()) add(com.google.gson.JsonNull.INSTANCE) else add(t.definitionTags)
+                    add(t.rules); add(t.score); add(com.google.gson.JsonParser.parseString(t.glossary)); add(t.sequence); add(t.termTags)
+                })
+            }.toString())
+            file("term_meta_bank_1.json", JsonArray().apply {
+                for (m in metas) add(JsonArray().apply { add(m.expression); add(m.mode); add(com.google.gson.JsonParser.parseString(m.data)) })
+            }.toString())
+            file("tag_bank_1.json", JsonArray().apply {
+                for (t in tags) add(JsonArray().apply { add(t.name); add(t.category); add(t.order); add(t.notes); add(t.score) })
+            }.toString())
+            file("kanji_bank_1.json", "[[\"日\",\"\",\"\",\"\",[],{}]]")
+            // The index last: a reader that stops at the first file would miss it.
+            file("index.json", index)
+        }
+        return bytes.toByteArray()
+    }
+
+    private class ListSink : DictionarySink {
+        val terms = ArrayList<Term>()
+        val metas = ArrayList<TermMeta>()
+        val tags = ArrayList<Tag>()
+        override fun term(term: Term) { terms.add(term) }
+        override fun termMeta(meta: TermMeta) { metas.add(meta) }
+        override fun tag(tag: Tag) { tags.add(tag) }
+    }
+
+    @Test
+    fun whatIsWrittenIsReadBack(): Unit = runBlocking {
+        checkAll(arbTerm) { terms ->
+            val metas = terms.take(3).map { TermMeta(it.expression, "freq", """{"value":5,"displayValue":"5"}""") }
+            val tags = listOf(Tag("n", "partOfSpeech", 0, "noun", 0.0))
+            val bytes = zip("""{"title":"Test","revision":"1","format":3}""", terms, metas, tags)
+            val index = YomitanZip.readIndex(ByteArrayInputStream(bytes))
+            assertEquals(DictionaryIndex("Test", "1", 3), index)
+            val sink = ListSink()
+            YomitanZip.readBanks(ByteArrayInputStream(bytes), sink)
+            assertEquals(terms, sink.terms)
+            assertEquals(metas, sink.metas)
+            assertEquals(tags, sink.tags)
+        }
+    }
+
+    @Test
+    fun versionIsAnAliasOfFormat() {
+        assertEquals(3, YomitanZip.parseIndex("""{"title":"T","revision":"r","version":3}""").format)
+    }
+}
+
+class LookupTest {
+
+    private val dictionary = listOf(
+        term("食べる", "たべる", "v1", 10.0),
+        term("食べ物", "たべもの", "", 5.0),
+        term("物", "もの", "", 1.0),
+        term("本", "ほん", "", 1.0),
+        term("パン", "ぱん", "", 1.0),
+        term("高い", "たかい", "adj-i", 3.0),
+        term("た", "", "", 0.0),
+    )
+
+    private fun term(expression: String, reading: String, rules: String, score: Double) =
+        StoredTerm(1, "Test", 0, Term(expression, reading, "", rules, score, "[\"x\"]", 0, ""))
+
+    private val source = object : TermSource {
+        override fun terms(texts: Collection<String>) =
+            dictionary.filter { it.term.expression in texts || it.term.reading in texts }
+    }
+
+    @Test
+    fun theLongestTermComesFirst() {
+        val found = Lookup.find("食べ物を食べた", 0, source).map { it.stored.term.expression to it.length }
+        assertEquals(listOf("食べ物" to 3, "食べる" to 2), found)
+    }
+
+    @Test
+    fun anInflectedVerbIsFound() {
+        val found = Lookup.find("食べ物を食べた", 4, source)
+        assertEquals("食べる", found.first().stored.term.expression)
+        assertEquals(3, found.first().length)
+        assertEquals(listOf("past"), found.first().reasons)
+    }
+
+    @Test
+    fun kanaMatchesTheReadingAndKatakanaMatchesToo() {
+        assertEquals("食べる", Lookup.find("たべます", 0, source).first().stored.term.expression)
+        assertEquals("パン", Lookup.find("ぱんを", 0, source).first().stored.term.expression)
+        assertEquals("パン", Lookup.find("パンを", 0, source).first().stored.term.expression)
+    }
+
+    @Test
+    fun aTermIsShownOnceWithItsLongestMatch() {
+        // 食べる is the text itself (3 characters) and the continuative 食べ + る (2 characters).
+        val found = Lookup.find("食べる", 0, source).filter { it.stored.term.expression == "食べる" }
+        assertEquals(listOf(3), found.map { it.length })
+        assertEquals(emptyList<String>(), found.first().reasons)
+    }
+
+    @Test
+    fun aNounWithNoRulesIsNotDeinflected() {
+        // 本た: the noun 本 is found for one character, not for two.
+        val found = Lookup.find("本た", 0, source)
+        assertEquals(listOf("本" to 1), found.map { it.stored.term.expression to it.length })
+    }
+
+    @Test
+    fun outOfRangeGivesNothing() {
+        assertTrue(Lookup.find("abc", 3, source).isEmpty())
+        assertTrue(Lookup.find("abc", -1, source).isEmpty())
+    }
+}
diff --git a/gradle.properties b/gradle.properties
new file mode 100644
index 0000000..0035b54
--- /dev/null
+++ b/gradle.properties
@@ -0,0 +1,5 @@
+org.gradle.jvmargs=-Xmx1536m -Dfile.encoding=UTF-8
+org.gradle.caching=true
+org.gradle.parallel=true
+kotlin.code.style=official
+android.useAndroidX=true
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
new file mode 100644
index 0000000..1e94b55
--- /dev/null
+++ b/gradle/libs.versions.toml
@@ -0,0 +1,27 @@
+[versions]
+agp = "9.2.0"
+kotlin = "2.3.21"
+coreKtx = "1.16.0"
+gson = "2.13.1"
+kotlinxCoroutines = "1.10.2"
+kotestProperty = "5.9.1"
+junit = "4.13.2"
+androidxTestRunner = "1.7.0"
+androidxTestJunit = "1.3.0"
+androidxTestCore = "1.7.0"
+
+[libraries]
+androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
+# Streaming JSON reader for the term banks of a dictionary. A term bank can be many megabytes;
+# the stream keeps one term in memory at a time.
+gson = { group = "com.google.code.gson", name = "gson", version.ref = "gson" }
+kotlinx-coroutines-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version.ref = "kotlinxCoroutines" }
+kotest-property = { group = "io.kotest", name = "kotest-property", version.ref = "kotestProperty" }
+junit = { group = "junit", name = "junit", version.ref = "junit" }
+androidx-test-runner = { group = "androidx.test", name = "runner", version.ref = "androidxTestRunner" }
+androidx-test-junit = { group = "androidx.test.ext", name = "junit", version.ref = "androidxTestJunit" }
+androidx-test-core = { group = "androidx.test", name = "core", version.ref = "androidxTestCore" }
+
+[plugins]
+android-application = { id = "com.android.application", version.ref = "agp" }
+kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..8bdaf60
Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..bb25ae9
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,9 @@
+#Tue Apr 28 00:13:17 CST 2026
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionSha256Sum=2ab2958f2a1e51120c326cad6f385153bb11ee93b3c216c5fccebfdfbb7ec6cb
+distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/gradlew b/gradlew
new file mode 100644
index 0000000..ef07e01
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,251 @@
+#!/bin/sh
+
+#
+# Copyright © 2015 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.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+#   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/HEAD/platforms/jvm/plugins-application/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
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
+
+# 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="\\\"\\\""
+
+
+# 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
+    if ! command -v java >/dev/null 2>&1
+    then
+        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
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+    case $MAX_FD in #(
+      max*)
+        # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+        # shellcheck disable=SC2039,SC3045
+        MAX_FD=$( ulimit -H -n ) ||
+            warn "Could not query maximum file descriptor limit"
+    esac
+    case $MAX_FD in  #(
+      '' | soft) :;; #(
+      *)
+        # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+        # shellcheck disable=SC2039,SC3045
+        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
+
+
+# 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"'
+
+# Collect all arguments for the java command:
+#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+#     and any embedded shellness will be escaped.
+#   * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+#     treated as '${Hostname}' itself on the command line.
+
+set -- \
+        "-Dorg.gradle.appname=$APP_BASE_NAME" \
+        -classpath "$CLASSPATH" \
+        -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
+        "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+    die "xargs is not available"
+fi
+
+# 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" "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 0000000..db3a6ac
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,94 @@
+@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
+@rem SPDX-License-Identifier: Apache-2.0
+@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=.
+@rem This is normally unused
+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% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 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!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/settings.gradle.kts b/settings.gradle.kts
new file mode 100644
index 0000000..127fbb4
--- /dev/null
+++ b/settings.gradle.kts
@@ -0,0 +1,26 @@
+pluginManagement {
+    repositories {
+        google {
+            content {
+                includeGroupByRegex("com\\.android.*")
+                includeGroupByRegex("com\\.google.*")
+                includeGroupByRegex("androidx.*")
+            }
+        }
+        mavenCentral()
+        gradlePluginPortal()
+    }
+}
+dependencyResolutionManagement {
+    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+    repositories {
+        google()
+        mavenCentral()
+    }
+}
+
+rootProject.name = "SubReadDictionary"
+
+// Plain Kotlin: the dictionary file format, the deinflector, the glossary text. Builds with a JDK alone.
+include(":core")
+include(":app")