Recently Written · git

subread-anki

One tap makes an Anki card on Android: word, definition, sentence, screenshot, audio. Works with any app, with SubRead Dictionary and SubRead Overlay.

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

Log | Files | Refs


commit 1832efcabb8918fee21e074d5b28e4999ef2498d
equwal <truex@equwal.com>
2026-09-25 02:13:31 -0700

Add SubRead Anki: one tap makes an Anki card from any app

The app takes a word from the text selection menu, the share sheet, or the
ADD intent of another app, and puts a card in AnkiDroid: the word, its reading
and definition from SubRead Dictionary, the sentence and a screenshot from the
capture service, the word audio, and the sentence read by the voice of the
device. The core module cuts the sentence, writes the furigana, and maps the
parts of a card to the fields of a note type.

 .gitignore                                         |  20 +
 LICENSE                                            | 662 +++++++++++++++++++++
 README.md                                          |  79 +++
 app/build.gradle.kts                               |  69 +++
 app/src/main/AndroidManifest.xml                   |  96 +++
 .../main/kotlin/space/subread/anki/AddActivity.kt  | 489 +++++++++++++++
 .../main/kotlin/space/subread/anki/AnkiDroid.kt    | 143 +++++
 .../kotlin/space/subread/anki/CaptureService.kt    | 142 +++++
 app/src/main/kotlin/space/subread/anki/Contract.kt |  36 ++
 .../main/kotlin/space/subread/anki/Dictionary.kt   |  86 +++
 .../main/kotlin/space/subread/anki/MainActivity.kt | 321 ++++++++++
 app/src/main/kotlin/space/subread/anki/Media.kt    |  68 +++
 app/src/main/kotlin/space/subread/anki/Notes.kt    |  96 +++
 app/src/main/kotlin/space/subread/anki/Request.kt  |  79 +++
 app/src/main/kotlin/space/subread/anki/Speech.kt   |  53 ++
 app/src/main/kotlin/space/subread/anki/Store.kt    |  70 +++
 app/src/main/res/drawable/icon.xml                 |  10 +
 app/src/main/res/drawable/sheet.xml                |   6 +
 app/src/main/res/values/strings.xml                |  95 +++
 app/src/main/res/values/styles.xml                 |  12 +
 app/src/main/res/xml/capture.xml                   |  14 +
 app/src/main/res/xml/files.xml                     |   5 +
 build.gradle.kts                                   |   5 +
 core/build.gradle.kts                              |  30 +
 .../main/kotlin/space/subread/anki/core/Card.kt    | 114 ++++
 .../kotlin/space/subread/anki/core/Furigana.kt     |  62 ++
 .../main/kotlin/space/subread/anki/core/Html.kt    |  39 ++
 .../main/kotlin/space/subread/anki/core/Kana.kt    |  22 +
 .../kotlin/space/subread/anki/core/Sentences.kt    |  88 +++
 .../kotlin/space/subread/anki/core/CardTest.kt     |  87 +++
 .../kotlin/space/subread/anki/core/FuriganaTest.kt |  61 ++
 .../space/subread/anki/core/SentencesTest.kt       |  93 +++
 docs/intent-api.md                                 |  78 +++
 fastlane/metadata/android/en-US/changelogs/1.txt   |   1 +
 .../metadata/android/en-US/full_description.txt    |   7 +
 .../metadata/android/en-US/short_description.txt   |   1 +
 fastlane/metadata/android/en-US/title.txt          |   1 +
 fdroid/space.subread.anki.yml                      |  26 +
 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 +
 45 files changed, 3778 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..dafa6b4
--- /dev/null
+++ b/README.md
@@ -0,0 +1,79 @@
+# SubRead Anki
+
+One tap makes an Anki card on Android: the word, its reading and its definition, the
+sentence the word is in, a screenshot of the screen, the word audio and the sentence audio.
+The card goes into [AnkiDroid](https://github.com/ankidroid/Anki-Android) on the device.
+Nothing leaves the device.
+
+It works with any app:
+
+- Select a word in any app and choose **"Add to Anki"** in the text selection menu.
+- Share a text to SubRead Anki. A single word becomes the card; in a longer text you tap
+  the word.
+- Tap **"Anki"** in the pop-up of [SubRead Dictionary](https://github.com/equwal/subread-dictionary),
+  or under a selected word in [SubRead Overlay](https://github.com/equwal/subread-overlay).
+- Any other app can send a card with one intent, see [docs/intent-api.md](docs/intent-api.md).
+
+## What goes on the card
+
+| Part | Where it comes from |
+|---|---|
+| Word, reading, definition | The app that sends the card, or else SubRead Dictionary, which reads Yomitan dictionaries (JMdict, Jitendex). The word goes on the card in its dictionary form. |
+| Sentence | The app that sends the card, or else the text around the word that you selected, when the capture service is on. The word is in bold. |
+| Screenshot | The capture service takes it at the moment you select the word, before a menu or a pop-up covers the app. |
+| Word audio | The app that sends the card, or else the first audio source of SubRead Dictionary (the local audio server file, or a remote source). |
+| Sentence audio | The voice of the device reads the sentence. Japanese text gets the Japanese voice. |
+| Source | The name of the app or the media the sentence is from. |
+
+The default note type "SubRead" has the fields Word, Reading, Definition, Sentence, Image,
+Audio, SentenceAudio and Source. The app makes it, and a "SubRead" deck, on the first card.
+Any other note type works: the settings map each field to a part of the card, with a guess
+from the field names. The word can also go into a field as `食[た]べる` for the furigana
+filter of Anki, or as a cloze.
+
+## How to use it
+
+1. Install AnkiDroid and open it once, so that it has a collection.
+2. Open SubRead Anki and allow it to write to the AnkiDroid database.
+3. Turn on the capture service in the accessibility settings of Android, for the sentence
+   and the screenshot. This step is optional. See [Privacy](#privacy).
+4. Install SubRead Dictionary and import a dictionary, for the definition, the reading and
+   the word audio. This step is optional: without it, the card has the word, the sentence,
+   the screenshot and the sentence audio, and you can type a definition.
+5. Select a word anywhere and choose "Add to Anki". A toast says "Added to Anki: 食べる".
+
+A card that misses its definition, or a text with no word chosen, shows as a sheet first:
+you complete it and tap "Add to Anki". The setting "Show the card first" makes every card
+show first.
+
+## Privacy
+
+The capture service is an accessibility service. Android gives it the text of the view in
+which you select a word, and the right to take a screenshot. The service keeps the last
+selection and the last screenshot in the cache of the app for the next card, and nothing
+else. It sends nothing anywhere. It is off until you turn it on, and the app works without
+it.
+
+The card goes to AnkiDroid on the same device. The app has no network permission.
+
+## Layout
+
+| Path | What |
+|---|---|
+| `core/` | Plain Kotlin: the sentence cut, the furigana, the fields of a card. Tests run with a JDK alone. |
+| `app/` | The Android app: the card sheet, the settings, the capture service, the AnkiDroid client, the voice. |
+| `docs/intent-api.md` | The intent that another app sends to add a card. |
+
+## Build
+
+```
+./gradlew :core:test :app:assembleDebug
+```
+
+The release build signs with the key in `SUBREAD_KEYSTORE_FILE` and `SUBREAD_KEYSTORE_PASSWORD`.
+`-PplayStore=true` leaves the Ko-fi link out.
+
+## License
+
+AGPL-3.0-only. The AnkiDroid content provider contract (the authority, the paths and the
+columns) is used as data; the API library of AnkiDroid is not included.
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
new file mode 100644
index 0000000..451f9bc
--- /dev/null
+++ b/app/build.gradle.kts
@@ -0,0 +1,69 @@
+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.anki"
+    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.anki"
+        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)
+
+    androidTestImplementation(libs.junit)
+    androidTestImplementation(libs.androidx.test.runner)
+    androidTestImplementation(libs.androidx.test.junit)
+    androidTestImplementation(libs.androidx.test.core)
+}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..9988eb6
--- /dev/null
+++ b/app/src/main/AndroidManifest.xml
@@ -0,0 +1,96 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+    <!-- The cards go into the database of AnkiDroid. AnkiDroid asks the user for this one. -->
+    <uses-permission android:name="com.ichi2.anki.permission.READ_WRITE_DATABASE" />
+
+    <!-- The two apps the card comes from and goes to. Android hides other apps without this list. -->
+    <queries>
+        <package android:name="com.ichi2.anki" />
+        <package android:name="space.subread.dictionary" />
+        <provider android:authorities="com.ichi2.anki.flashcards" />
+        <provider android:authorities="space.subread.dictionary.lookup" />
+        <provider android:authorities="space.subread.dictionary.debug.lookup" />
+    </queries>
+
+    <application
+        android:allowBackup="true"
+        android:icon="@drawable/icon"
+        android:label="@string/app_name"
+        android:supportsRtl="true"
+        android:theme="@android:style/Theme.DeviceDefault.Light.NoActionBar">
+
+        <!-- The settings: AnkiDroid, the deck and the note type, the capture service, 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 card. Four ways in: the text selection menu of Android ("Add to Anki" in the
+            menu), the share sheet with a text or an image, and the ADD intent of another app
+            such as SubRead Dictionary. It has no task of its own, so it opens over the app that
+            sent the word, and it is see-through until the card shows.
+        -->
+        <activity
+            android:name=".AddActivity"
+            android:excludeFromRecents="true"
+            android:exported="true"
+            android:label="@string/add_label"
+            android:launchMode="singleTop"
+            android:taskAffinity=""
+            android:theme="@style/Sheet">
+            <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="android.intent.action.SEND" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <data android:mimeType="image/*" />
+            </intent-filter>
+            <intent-filter>
+                <action android:name="space.subread.anki.action.ADD" />
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
+        </activity>
+
+        <!--
+            Keeps the last text selection of another app and takes a screenshot at that moment.
+            Off until the user turns it on in the accessibility settings. See CaptureService.
+        -->
+        <service
+            android:name=".CaptureService"
+            android:exported="true"
+            android:label="@string/capture_label"
+            android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
+            <intent-filter>
+                <action android:name="android.accessibilityservice.AccessibilityService" />
+            </intent-filter>
+            <meta-data
+                android:name="android.accessibilityservice"
+                android:resource="@xml/capture" />
+        </service>
+
+        <!-- AnkiDroid reads the files of a card through this provider. -->
+        <provider
+            android:name="androidx.core.content.FileProvider"
+            android:authorities="${applicationId}.files"
+            android:exported="false"
+            android:grantUriPermissions="true">
+            <meta-data
+                android:name="android.support.FILE_PROVIDER_PATHS"
+                android:resource="@xml/files" />
+        </provider>
+    </application>
+</manifest>
diff --git a/app/src/main/kotlin/space/subread/anki/AddActivity.kt b/app/src/main/kotlin/space/subread/anki/AddActivity.kt
new file mode 100644
index 0000000..c8c1f9b
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/anki/AddActivity.kt
@@ -0,0 +1,489 @@
+package space.subread.anki
+
+import android.annotation.SuppressLint
+import android.app.Activity
+import android.app.AlertDialog
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.graphics.BitmapFactory
+import android.graphics.Color
+import android.graphics.Typeface
+import android.icu.text.BreakIterator
+import android.os.Bundle
+import android.os.Handler
+import android.os.Looper
+import android.text.Html
+import android.text.InputType
+import android.view.Gravity
+import android.view.MotionEvent
+import android.view.View
+import android.view.ViewGroup
+import android.widget.Button
+import android.widget.CheckBox
+import android.widget.EditText
+import android.widget.FrameLayout
+import android.widget.ImageView
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
+import android.widget.Toast
+import androidx.core.net.toUri
+import space.subread.anki.core.Kana
+import space.subread.anki.core.Sentence
+import space.subread.anki.core.Sentences
+import java.io.File
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+import kotlin.concurrent.thread
+
+/**
+ * Makes one card. The window is see-through while the parts of the card are gathered: the
+ * definition and the audio from SubRead Dictionary, the sentence and the screenshot from the
+ * capture service. A complete card goes to Anki at once, with a toast. A card that misses a
+ * part, or one the user wants to see, shows as a sheet at the bottom of the screen.
+ */
+class AddActivity : Activity() {
+
+    private lateinit var store: Store
+    private lateinit var anki: AnkiDroid
+    private lateinit var dictionary: Dictionary
+    private lateinit var notes: Notes
+    private val handler = Handler(Looper.getMainLooper())
+    private var request: Request? = null
+    private var draft = Draft()
+    private var sheet: View? = null
+    private var busy = false
+
+    /** The user's choice on the sheet. Before the sheet: the settings. */
+    private var wordAudioWanted = true
+    private var sentenceAudioWanted = true
+
+    // The fields of the sheet, when it shows.
+    private var wordField: EditText? = null
+    private var readingField: EditText? = null
+    private var definitionField: EditText? = null
+    private var sentenceField: EditText? = null
+    private var tagsField: EditText? = null
+
+    override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+        store = Store(this)
+        anki = AnkiDroid(this)
+        dictionary = Dictionary(this)
+        notes = Notes(this, store, anki)
+        begin(intent)
+    }
+
+    override fun onNewIntent(intent: Intent) {
+        super.onNewIntent(intent)
+        setIntent(intent)
+        begin(intent)
+    }
+
+    private fun begin(intent: Intent) {
+        draft = Draft()
+        sheet?.let { (it.parent as? ViewGroup)?.removeView(it) }
+        sheet = null
+        sentenceAudioWanted = store.sentenceAudio
+        wordAudioWanted = true
+        val request = Request.of(intent, referrer?.takeIf { it.scheme == "android-app" }?.host)
+        if (request == null) return finishWith(getString(R.string.no_text))
+        this.request = request
+        Media.clean(this)
+        when {
+            !anki.installed -> AlertDialog.Builder(this)
+                .setMessage(R.string.anki_missing)
+                .setPositiveButton(R.string.anki_get) { _, _ -> open(AnkiDroid.INSTALL) }
+                .setNegativeButton(R.string.cancel, null)
+                .setOnDismissListener { finish() }
+                .show()
+            !anki.permitted -> requestPermissions(arrayOf(AnkiDroid.PERMISSION), PERMISSION)
+            else -> start()
+        }
+    }
+
+    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
+        if (requestCode != PERMISSION) return
+        if (grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) start() else finishWith(getString(R.string.permission_denied))
+    }
+
+    private fun start() {
+        val request = this.request ?: return
+        busy = true
+        thread(name = "gather") {
+            runCatching { gather(request) }
+            runOnUiThread {
+                busy = false
+                decide(request)
+            }
+        }
+    }
+
+    /** Fills the draft: what came with the intent first, then the dictionary and the capture service. Off the main thread. */
+    private fun gather(request: Request) {
+        val now = System.currentTimeMillis()
+        draft.surface = request.word
+        draft.word = request.word
+        draft.reading = request.reading
+        draft.definition = request.definition
+        draft.text = request.text
+        draft.source = request.source
+        draft.url = request.url
+        draft.tags = request.tags
+        val selection = Capture.selection?.takeIf { now - it.at < RECENT_MS }
+        val shot = Capture.shot?.takeIf { now - it.at < RECENT_MS && it.file.isFile }
+
+        // The image: the one that came, else the screenshot of the selection, else a fresh one.
+        draft.image = request.image?.let { Media.copy(this, it, "image", "image") }
+        if (draft.image == null && store.image) {
+            draft.image = shot?.let { copyOf(it.file) } ?: if (request.screenshot) freshShot() else null
+        }
+
+        // The word, the reading and the definition, from SubRead Dictionary when they did not come.
+        if (draft.word.isNotEmpty() && draft.definition.isEmpty() && store.dictionary && dictionary.installed) {
+            val entries = dictionary.lookup(draft.word)
+            val first = entries.firstOrNull()
+            if (first != null) {
+                draft.word = first.expression
+                if (draft.reading.isEmpty()) draft.reading = first.reading
+                draft.definition = Dictionary.definition(entries)
+            }
+        }
+
+        draft.sentence = sentenceFor(request, selection)
+
+        // The word audio: the one that came, else the first source of SubRead Dictionary.
+        draft.audio = request.audio?.let { Media.copy(this, it, "word", "audio") }
+        if (draft.audio == null && store.audio && draft.word.isNotEmpty() && dictionary.installed) {
+            draft.audio = dictionary.audio(draft.word, draft.reading)
+        }
+        draft.sentenceAudio = request.sentenceAudio?.let { Media.copy(this, it, "sentence", "audio") }
+
+        if (draft.source.isEmpty()) draft.source = appName(request.caller ?: selection?.packageName ?: shot?.packageName)
+    }
+
+    /**
+     * The sentence: the one that came, when it has the word and more; else the text around the
+     * selection that the capture service saw; else the one that came; else the word alone.
+     */
+    private fun sentenceFor(request: Request, selection: Capture.Selection?): Sentence? {
+        val surface = draft.surface
+        if (surface.isEmpty()) return null
+        val given = request.sentence
+        val at = given.indexOf(surface)
+        if (at >= 0 && given.length > surface.length) return Sentence(given, at, at + surface.length)
+        if (selection != null) {
+            if (selection.word.trim() == surface) return Sentences.around(selection.text, selection.start, selection.end)
+            val found = selection.text.indexOf(surface)
+            if (found >= 0) return Sentences.around(selection.text, found, found + surface.length)
+        }
+        if (given.isNotEmpty()) return if (at >= 0) Sentence(given, at, at + surface.length) else Sentence(given, given.length, given.length)
+        return Sentence.of(surface)
+    }
+
+    /** A screenshot now, through the capture service. Null without the service, or when Android refuses. */
+    private fun freshShot(): File? {
+        val service = CaptureService.instance ?: return null
+        val done = CountDownLatch(1)
+        var out: File? = null
+        handler.post {
+            service.screenshot { file ->
+                out = file?.let { copyOf(it) }
+                done.countDown()
+            }
+        }
+        done.await(SHOT_WAIT_MS, TimeUnit.MILLISECONDS)
+        return out
+    }
+
+    /** The screenshot of the service goes when the next one comes: the card keeps its own copy. */
+    private fun copyOf(file: File): File? = runCatching { file.copyTo(Media.file(this, "image", "jpg"), overwrite = true) }.getOrNull()
+
+    private fun appName(packageName: String?): String {
+        if (packageName == null || packageName == this.packageName) return ""
+        return runCatching { packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, 0)).toString() }.getOrDefault("")
+    }
+
+    /** A complete card goes at once when the settings say so. Otherwise the sheet shows. */
+    private fun decide(request: Request) {
+        val incomplete = draft.word.isEmpty() || (draft.definition.isEmpty() && store.dictionary && dictionary.installed)
+        if (request.show || !store.addAtOnce || incomplete) showSheet() else add()
+    }
+
+    private fun add() {
+        if (busy) return
+        busy = true
+        sheet?.findViewWithTag<Button>(TAG_ADD)?.apply {
+            isEnabled = false
+            text = getString(R.string.adding)
+        }
+        thread(name = "add") {
+            val result = runCatching {
+                if (!wordAudioWanted) draft.audio = null
+                val sentence = draft.sentence
+                if (draft.sentenceAudio == null && sentenceAudioWanted && sentence != null) draft.sentenceAudio = speak(sentence)
+                if (!sentenceAudioWanted) draft.sentenceAudio = null
+                notes.add(draft)
+            }
+            runOnUiThread {
+                busy = false
+                result.onSuccess { added ->
+                    val message = if (added.duplicates > 0) getString(R.string.added_again, added.word, added.duplicates) else getString(R.string.added, added.word)
+                    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
+                    setResult(RESULT_OK, Intent().putExtra(Contract.EXTRA_NOTE_ID, added.noteId))
+                    finish()
+                }.onFailure {
+                    showSheet(getString(R.string.anki_error, it.message ?: it.javaClass.simpleName))
+                }
+            }
+        }
+    }
+
+    /** The voice of the device reads the sentence into a file. Null when it cannot. Off the main thread. */
+    private fun speak(sentence: Sentence): File? {
+        if (sentence.text.isBlank() || sentence.text.length > SPEECH_MAX) return null
+        val file = Media.file(this, "sentence", "wav")
+        if (Speech(this).synthesize(sentence.text, file, Kana.hasJapanese(sentence.text))) return file
+        file.delete()
+        return null
+    }
+
+    // The sheet.
+
+    @SuppressLint("ClickableViewAccessibility") // The touch listener finds the character under the finger; it calls performClick itself.
+    private fun showSheet(error: String? = null) {
+        sheet?.let { (it.parent as? ViewGroup)?.removeView(it) }
+        val panel = LinearLayout(this).apply {
+            orientation = LinearLayout.VERTICAL
+            setBackgroundResource(R.drawable.sheet)
+            setPadding(dp(16), dp(12), dp(16), dp(12))
+            isClickable = true
+        }
+        val header = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
+        header.addView(TextView(this).apply {
+            text = getString(R.string.sheet_title)
+            textSize = 18f
+            setTypeface(typeface, Typeface.BOLD)
+            setTextColor(Color.BLACK)
+        }, LinearLayout.LayoutParams(0, -2, 1f))
+        header.addView(smallButton(getString(R.string.settings)) { startActivity(Intent(this, MainActivity::class.java)) })
+        header.addView(smallButton(getString(R.string.close)) { finish() })
+        panel.addView(header, wide(0))
+        if (error != null) panel.addView(label(error, Color.RED))
+
+        val body = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
+        val pick = draft.word.isEmpty() && draft.text.isNotEmpty()
+        if (pick) {
+            body.addView(label(getString(R.string.pick_word), Color.DKGRAY))
+            body.addView(TextView(this).apply {
+                text = draft.text
+                textSize = 18f
+                setTextColor(Color.BLACK)
+                setPadding(0, dp(4), 0, dp(4))
+                setOnTouchListener { view, event ->
+                    if (event.action == MotionEvent.ACTION_UP) {
+                        val at = (view as TextView).getOffsetForPosition(event.x, event.y)
+                        if (at in draft.text.indices) pickWord(at)
+                        view.performClick()
+                    }
+                    true
+                }
+            }, wide(4))
+        }
+        body.addView(label(getString(R.string.word), Color.DKGRAY, 13f))
+        wordField = field(draft.word, single = true).also { body.addView(it, wide(0)) }
+        body.addView(label(getString(R.string.reading), Color.DKGRAY, 13f))
+        readingField = field(draft.reading, single = true).also { body.addView(it, wide(0)) }
+
+        body.addView(label(getString(R.string.definition), Color.DKGRAY, 13f))
+        definitionField = null
+        if (draft.definition.isNotEmpty()) {
+            body.addView(TextView(this).apply {
+                text = Html.fromHtml(draft.definition, Html.FROM_HTML_MODE_COMPACT)
+                textSize = 15f
+                setTextColor(Color.BLACK)
+            }, wide(0))
+        } else {
+            val why = if (dictionary.installed) R.string.no_definition_found else R.string.no_definition
+            body.addView(label(getString(why), Color.DKGRAY))
+            definitionField = field("", single = false).also { body.addView(it, wide(0)) }
+        }
+
+        body.addView(label(getString(R.string.sentence), Color.DKGRAY, 13f))
+        sentenceField = field(draft.sentence?.text ?: "", single = false).also { body.addView(it, wide(0)) }
+
+        body.addView(label(getString(R.string.image), Color.DKGRAY, 13f))
+        val image = draft.image
+        if (image != null) {
+            val row = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
+            row.addView(ImageView(this).apply {
+                setImageBitmap(thumbnail(image))
+                adjustViewBounds = true
+                scaleType = ImageView.ScaleType.FIT_START
+            }, LinearLayout.LayoutParams(0, dp(110), 1f))
+            row.addView(smallButton(getString(R.string.remove)) {
+                draft.image = null
+                showSheet(error)
+            })
+            body.addView(row, wide(0))
+        } else {
+            body.addView(label(getString(R.string.image_none), Color.DKGRAY))
+        }
+
+        body.addView(CheckBox(this).apply {
+            text = getString(R.string.word_audio)
+            isEnabled = draft.audio != null
+            isChecked = draft.audio != null && wordAudioWanted
+            setTextColor(Color.BLACK)
+            setOnCheckedChangeListener { _, checked -> wordAudioWanted = checked }
+        }, wide(4))
+        body.addView(CheckBox(this).apply {
+            text = getString(R.string.sentence_audio)
+            isChecked = sentenceAudioWanted
+            setTextColor(Color.BLACK)
+            setOnCheckedChangeListener { _, checked -> sentenceAudioWanted = checked }
+        }, wide(0))
+
+        val deckRow = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
+        deckRow.addView(label(getString(R.string.deck, store.deckName.ifEmpty { getString(R.string.deck_default) }), Color.BLACK), LinearLayout.LayoutParams(0, -2, 1f))
+        deckRow.addView(smallButton(getString(R.string.choose)) { chooseDeck { showSheet(error) } })
+        body.addView(deckRow, wide(4))
+
+        body.addView(label(getString(R.string.tags_short) + " (+ " + store.tags + ")", Color.DKGRAY, 13f))
+        tagsField = field(draft.tags, single = true).also { body.addView(it, wide(0)) }
+
+        val maxHeight = (resources.displayMetrics.heightPixels * 0.6).toInt()
+        val scroll = object : ScrollView(this) {
+            override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) =
+                super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST))
+        }
+        scroll.addView(body)
+        panel.addView(scroll, wide(4))
+
+        val buttons = LinearLayout(this).apply { gravity = Gravity.END }
+        buttons.addView(smallButton(getString(R.string.cancel)) { finish() })
+        buttons.addView(Button(this).apply {
+            text = getString(R.string.add)
+            tag = TAG_ADD
+            isAllCaps = false
+            setTypeface(typeface, Typeface.BOLD)
+            setOnClickListener {
+                readSheet()
+                if (draft.word.isEmpty()) Toast.makeText(this@AddActivity, R.string.no_word, Toast.LENGTH_SHORT).show() else add()
+            }
+        })
+        panel.addView(buttons, wide(8))
+
+        val root = FrameLayout(this).apply { setOnClickListener { finish() } }
+        root.addView(panel, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM))
+        setContentView(root)
+        sheet = root
+    }
+
+    /** The user tapped a character of the text: the word there, from the dictionary or by the word breaks of the language. */
+    private fun pickWord(at: Int) {
+        if (busy) return
+        busy = true
+        val text = draft.text
+        thread(name = "pick") {
+            val entries = if (store.dictionary && dictionary.installed) dictionary.lookup(text.substring(at)) else emptyList()
+            val first = entries.firstOrNull()
+            val end = if (first != null) at + first.length else wordEnd(text, at)
+            draft.surface = text.substring(at, end)
+            draft.word = first?.expression ?: draft.surface
+            draft.reading = first?.reading ?: ""
+            draft.definition = Dictionary.definition(entries)
+            draft.sentence = Sentences.around(text, at, end)
+            draft.audio = if (store.audio && dictionary.installed) dictionary.audio(draft.word, draft.reading) else null
+            runOnUiThread {
+                busy = false
+                showSheet()
+            }
+        }
+    }
+
+    /** The end of the word at [at], by the word breaks of the language of the text. */
+    private fun wordEnd(text: String, at: Int): Int {
+        val words = BreakIterator.getWordInstance()
+        words.setText(text)
+        val end = words.following(at)
+        return if (end == BreakIterator.DONE || end <= at) minOf(text.length, at + 1) else end
+    }
+
+    /** What the user typed on the sheet goes into the draft. */
+    private fun readSheet() {
+        draft.word = wordField?.text?.toString()?.trim() ?: draft.word
+        draft.reading = readingField?.text?.toString()?.trim() ?: draft.reading
+        definitionField?.text?.toString()?.trim()?.takeIf { it.isNotEmpty() }?.let { draft.definition = space.subread.anki.core.Html.escape(it).replace("\n", "<br>") }
+        draft.tags = tagsField?.text?.toString()?.trim() ?: draft.tags
+        val text = sentenceField?.text?.toString()?.trim() ?: return
+        draft.sentence = when {
+            text.isEmpty() -> null
+            else -> {
+                val surface = draft.surface.ifEmpty { draft.word }
+                val at = text.indexOf(surface).takeIf { surface.isNotEmpty() } ?: -1
+                if (at >= 0) Sentence(text, at, at + surface.length) else Sentence(text, text.length, text.length)
+            }
+        }
+    }
+
+    private fun chooseDeck(then: () -> Unit) {
+        thread {
+            val decks = runCatching { anki.decks() }.getOrDefault(emptyMap()).toList().sortedBy { it.second }
+            runOnUiThread {
+                if (decks.isEmpty()) return@runOnUiThread
+                AlertDialog.Builder(this).setItems(decks.map { it.second }.toTypedArray()) { _, which ->
+                    store.deckId = decks[which].first
+                    store.deckName = decks[which].second
+                    then()
+                }.show()
+            }
+        }
+    }
+
+    private fun thumbnail(file: File) = BitmapFactory.decodeFile(file.path, BitmapFactory.Options().apply { inSampleSize = 4 })
+
+    private fun finishWith(message: String) {
+        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
+        finish()
+    }
+
+    private fun open(link: String) {
+        runCatching { startActivity(Intent(Intent.ACTION_VIEW, link.toUri())) }
+    }
+
+    private fun label(value: String, color: Int, size: Float = 15f) = TextView(this).apply {
+        text = value
+        textSize = size
+        setTextColor(color)
+    }
+
+    private fun field(value: String, single: Boolean) = EditText(this).apply {
+        setText(value)
+        setTextColor(Color.BLACK)
+        textSize = 16f
+        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
+    }
+
+    private fun smallButton(text: String, onClick: () -> Unit) = Button(this).apply {
+        this.text = text
+        isAllCaps = false
+        textSize = 13f
+        setOnClickListener { onClick() }
+    }
+
+    private fun wide(top: Int) = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(top) }
+
+    private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
+
+    private companion object {
+        const val PERMISSION = 1
+        const val TAG_ADD = "add"
+        /** A selection or a screenshot older than this is not the one the card is about. */
+        const val RECENT_MS = 90_000L
+        const val SHOT_WAIT_MS = 2_500L
+        /** The voice reads a sentence up to this long. */
+        const val SPEECH_MAX = 400
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/anki/AnkiDroid.kt b/app/src/main/kotlin/space/subread/anki/AnkiDroid.kt
new file mode 100644
index 0000000..5d22e1f
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/anki/AnkiDroid.kt
@@ -0,0 +1,143 @@
+package space.subread.anki
+
+import android.content.ContentValues
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.os.Build
+import androidx.core.net.toUri
+
+/**
+ * Talks to AnkiDroid through its content provider. The contract is the FlashCardsContract of
+ * AnkiDroid: the authority, the paths and the columns below. The API library of AnkiDroid is not
+ * used: it comes from JitPack alone, and F-Droid builds from Maven Central and source alone.
+ *
+ * Each call can throw: AnkiDroid is not installed, the permission is not given, or AnkiDroid
+ * has no collection open. The caller shows the message.
+ */
+class AnkiDroid(private val context: Context) {
+
+    /** A note type: its id, its name, and its fields in order. */
+    data class Model(val id: Long, val name: String, val fields: List<String>)
+
+    private val resolver get() = context.contentResolver
+
+    /** The package of AnkiDroid, or null when no AnkiDroid with the provider is installed. */
+    val packageName: String?
+        get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+            context.packageManager.resolveContentProvider(AUTHORITY, PackageManager.ComponentInfoFlags.of(0))?.packageName
+        } else {
+            @Suppress("DEPRECATION")
+            context.packageManager.resolveContentProvider(AUTHORITY, 0)?.packageName
+        }
+
+    val installed: Boolean get() = packageName != null
+
+    val permitted: Boolean get() = context.checkSelfPermission(PERMISSION) == PackageManager.PERMISSION_GRANTED
+
+    fun decks(): Map<Long, String> = resolver.query(DECKS, null, null, null, null)?.use { c ->
+        buildMap {
+            while (c.moveToNext()) put(c.getLong(c.getColumnIndexOrThrow("deck_id")), c.getString(c.getColumnIndexOrThrow("deck_name")))
+        }
+    } ?: emptyMap()
+
+    fun addDeck(name: String): Long? =
+        resolver.insert(DECKS, ContentValues().apply { put("deck_name", name) })?.lastPathSegment?.toLongOrNull()
+
+    fun models(): List<Model> = resolver.query(MODELS, null, null, null, null)?.use { c ->
+        buildList {
+            while (c.moveToNext()) {
+                add(
+                    Model(
+                        c.getLong(c.getColumnIndexOrThrow("_id")),
+                        c.getString(c.getColumnIndexOrThrow("name")),
+                        c.getString(c.getColumnIndexOrThrow("field_names")).split(SEPARATOR),
+                    ),
+                )
+            }
+        }
+    } ?: emptyList()
+
+    fun model(id: Long): Model? = models().firstOrNull { it.id == id }
+
+    /** Makes a note type with one card. Returns its id. */
+    fun addModel(name: String, fields: List<String>, cardName: String, front: String, back: String, css: String): Long? {
+        val values = ContentValues().apply {
+            put("name", name)
+            put("field_names", fields.joinToString(SEPARATOR))
+            put("num_cards", 1)
+            put("css", css)
+        }
+        val model = resolver.insert(MODELS, values) ?: return null
+        val template = Uri.withAppendedPath(Uri.withAppendedPath(model, "templates"), "0")
+        val templateValues = ContentValues().apply {
+            put("card_template_name", cardName)
+            put("question_format", front)
+            put("answer_format", back)
+        }
+        resolver.update(template, templateValues, null, null)
+        return model.lastPathSegment?.toLongOrNull()
+    }
+
+    /**
+     * Copies a file into the media folder of Anki. AnkiDroid reads the file through the URI, so
+     * it gets the read permission first. Returns the name that a field refers to, or null.
+     */
+    fun addMedia(file: Uri, preferredName: String): String? {
+        val anki = packageName ?: return null
+        context.grantUriPermission(anki, file, Intent.FLAG_GRANT_READ_URI_PERMISSION)
+        try {
+            val values = ContentValues().apply {
+                put("file_uri", file.toString())
+                put("preferred_name", preferredName.replace(' ', '_'))
+            }
+            val stored = resolver.insert(MEDIA, values) ?: return null
+            // The path of the answer is the file name with a slash in front.
+            return stored.path?.trimStart('/')?.takeIf { it.isNotEmpty() }
+        } finally {
+            context.revokeUriPermission(file, Intent.FLAG_GRANT_READ_URI_PERMISSION)
+        }
+    }
+
+    /** Adds a note and puts its cards in the deck. Returns the id of the note, or null. */
+    fun addNote(modelId: Long, deckId: Long, fields: List<String>, tags: Collection<String>): Long? {
+        val values = ContentValues().apply {
+            put("mid", modelId)
+            put("flds", fields.joinToString(SEPARATOR))
+            put("tags", tags.joinToString(" "))
+        }
+        val note = resolver.insert(NOTES, values) ?: return null
+        val cards = Uri.withAppendedPath(note, "cards")
+        resolver.query(cards, null, null, null, null)?.use { c ->
+            while (c.moveToNext()) {
+                val ord = c.getString(c.getColumnIndexOrThrow("ord"))
+                resolver.update(Uri.withAppendedPath(cards, ord), ContentValues().apply { put("deck_id", deckId) }, null, null)
+            }
+        }
+        return note.lastPathSegment?.toLongOrNull()
+    }
+
+    /** How many notes of the note type have this first field. Zero when the search fails. */
+    fun duplicates(model: Model, first: String): Int = runCatching {
+        val key = first.replace("\"", "").replace("*", "").replace("_", "")
+        if (key.isBlank()) return 0
+        val search = "${model.fields[0]}:\"$key\" note:\"${model.name}\""
+        resolver.query(NOTES, arrayOf("_id"), search, null, null)?.use { it.count } ?: 0
+    }.getOrDefault(0)
+
+    companion object {
+        const val AUTHORITY = "com.ichi2.anki.flashcards"
+        const val PERMISSION = "com.ichi2.anki.permission.READ_WRITE_DATABASE"
+        const val PACKAGE = "com.ichi2.anki"
+        const val INSTALL = "https://github.com/ankidroid/Anki-Android/releases/latest"
+        private val ROOT = "content://$AUTHORITY".toUri()
+        private val NOTES: Uri = Uri.withAppendedPath(ROOT, "notes")
+        private val MODELS: Uri = Uri.withAppendedPath(ROOT, "models")
+        private val DECKS: Uri = Uri.withAppendedPath(ROOT, "decks")
+        private val MEDIA: Uri = Uri.withAppendedPath(ROOT, "media")
+
+        /** Anki keeps the fields of a note in one string, with this character between them. */
+        private const val SEPARATOR = "\u001f"
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/anki/CaptureService.kt b/app/src/main/kotlin/space/subread/anki/CaptureService.kt
new file mode 100644
index 0000000..c26b78f
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/anki/CaptureService.kt
@@ -0,0 +1,142 @@
+package space.subread.anki
+
+import android.accessibilityservice.AccessibilityService
+import android.content.ComponentName
+import android.content.Context
+import android.graphics.Bitmap
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.provider.Settings
+import android.view.Display
+import android.view.accessibility.AccessibilityEvent
+import androidx.core.graphics.scale
+import java.io.File
+
+/**
+ * What the capture service saw last: the text selection of another app, and a screenshot from
+ * that moment. The card takes the sentence from the one and the image from the other.
+ */
+object Capture {
+
+    /** A selection in an app: the whole text of the view, and the selected part of it. */
+    data class Selection(val packageName: String, val text: String, val start: Int, val end: Int, val at: Long) {
+        val word: String get() = text.substring(start, end)
+    }
+
+    data class Shot(val file: File, val packageName: String?, val at: Long)
+
+    @Volatile
+    var selection: Selection? = null
+
+    @Volatile
+    var shot: Shot? = null
+
+    /** The app in front, the last one that was not this app. */
+    @Volatile
+    var front: String? = null
+
+    /** True when the user turned the service on in the accessibility settings of Android. */
+    fun isEnabled(context: Context): Boolean {
+        val me = ComponentName(context, CaptureService::class.java)
+        val enabled = Settings.Secure.getString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES) ?: return false
+        return enabled.split(':').any { ComponentName.unflattenFromString(it) == me }
+    }
+}
+
+/**
+ * The accessibility service. It listens to two kinds of events: a text selection changed, and a
+ * window came to the front. After a selection it takes a screenshot, before a menu or a pop-up
+ * can cover the app. It reads no other content and sends nothing anywhere.
+ */
+class CaptureService : AccessibilityService() {
+
+    private val handler = Handler(Looper.getMainLooper())
+    private val shootLater = Runnable { screenshot { } }
+
+    override fun onServiceConnected() {
+        instance = this
+    }
+
+    override fun onUnbind(intent: android.content.Intent?): Boolean {
+        instance = null
+        return super.onUnbind(intent)
+    }
+
+    override fun onDestroy() {
+        instance = null
+        super.onDestroy()
+    }
+
+    override fun onInterrupt() = Unit
+
+    override fun onAccessibilityEvent(event: AccessibilityEvent) {
+        val app = event.packageName?.toString() ?: return
+        if (app == packageName) return
+        when (event.eventType) {
+            AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> if (app != AnkiDroid.PACKAGE && app != SYSTEM_UI) Capture.front = app
+            AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED -> selected(app, event)
+            else -> Unit
+        }
+    }
+
+    private fun selected(app: String, event: AccessibilityEvent) {
+        val node = event.source
+        val text = node?.text?.toString() ?: event.text.joinToString("")
+        val start = node?.textSelectionStart ?: event.fromIndex
+        val end = node?.textSelectionEnd ?: event.toIndex
+        if (start < 0 || end <= start || end > text.length) return
+        Capture.selection = Capture.Selection(app, text, start, end, System.currentTimeMillis())
+        // The screenshot waits a moment: the selection handles settle, and Android allows one shot in a third of a second.
+        handler.removeCallbacks(shootLater)
+        handler.postDelayed(shootLater, SHOT_DELAY_MS)
+    }
+
+    /**
+     * Takes a screenshot and keeps it as the last shot. The callback gets the file, or null when
+     * Android refuses: before Android 11, or a shot too soon after the last one. From the main thread.
+     */
+    fun screenshot(callback: (File?) -> Unit) {
+        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return callback(null)
+        takeScreenshot(
+            Display.DEFAULT_DISPLAY,
+            mainExecutor,
+            object : TakeScreenshotCallback {
+                override fun onSuccess(result: ScreenshotResult) {
+                    val buffer = result.hardwareBuffer
+                    val bitmap = Bitmap.wrapHardwareBuffer(buffer, result.colorSpace)?.copy(Bitmap.Config.ARGB_8888, false)
+                    buffer.close()
+                    val file = bitmap?.let { save(it) }
+                    if (file != null) {
+                        Capture.shot?.file?.delete()
+                        Capture.shot = Capture.Shot(file, Capture.front, System.currentTimeMillis())
+                    }
+                    callback(file)
+                }
+
+                override fun onFailure(errorCode: Int) = callback(null)
+            },
+        )
+    }
+
+    /** The screenshot as a JPEG in the cache, no side longer than [MAX_SIDE] pixels. */
+    private fun save(bitmap: Bitmap): File? = runCatching {
+        val scale = MAX_SIDE.toFloat() / maxOf(bitmap.width, bitmap.height)
+        val scaled = if (scale < 1f) bitmap.scale((bitmap.width * scale).toInt(), (bitmap.height * scale).toInt()) else bitmap
+        val file = Media.file(this, "shot", "jpg")
+        file.outputStream().use { scaled.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, it) }
+        file
+    }.getOrNull()
+
+    companion object {
+        const val SHOT_DELAY_MS = 400L
+        const val MAX_SIDE = 1280
+        const val JPEG_QUALITY = 85
+        private const val SYSTEM_UI = "com.android.systemui"
+
+        /** The service that Android runs now; null when the user did not turn it on. */
+        @Volatile
+        var instance: CaptureService? = null
+            private set
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/anki/Contract.kt b/app/src/main/kotlin/space/subread/anki/Contract.kt
new file mode 100644
index 0000000..8585ff3
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/anki/Contract.kt
@@ -0,0 +1,36 @@
+package space.subread.anki
+
+/**
+ * The intent that another app sends to add a card: SubRead Dictionary, SubRead Overlay, a
+ * reader. The strings are the contract, see docs/intent-api.md. Another app copies them; it
+ * needs no code of this app.
+ */
+object Contract {
+    const val PACKAGE = "space.subread.anki"
+    const val ACTION_ADD = "space.subread.anki.action.ADD"
+
+    /** The word, in its dictionary form when the sender knows it. */
+    const val EXTRA_WORD = "space.subread.anki.extra.WORD"
+    const val EXTRA_READING = "space.subread.anki.extra.READING"
+    /** The definition as simple HTML. */
+    const val EXTRA_DEFINITION = "space.subread.anki.extra.DEFINITION"
+    /** The sentence the word is in, as plain text. */
+    const val EXTRA_SENTENCE = "space.subread.anki.extra.SENTENCE"
+    /** A text with no word chosen yet: the user taps the word in it. */
+    const val EXTRA_TEXT = "space.subread.anki.extra.TEXT"
+    /** Content URIs, as strings. The sender grants the read permission through the clip data of the intent. */
+    const val EXTRA_IMAGE = "space.subread.anki.extra.IMAGE"
+    const val EXTRA_AUDIO = "space.subread.anki.extra.AUDIO"
+    const val EXTRA_SENTENCE_AUDIO = "space.subread.anki.extra.SENTENCE_AUDIO"
+    /** Where the sentence is from: a book, a video, an app. */
+    const val EXTRA_SOURCE = "space.subread.anki.extra.SOURCE"
+    const val EXTRA_URL = "space.subread.anki.extra.URL"
+    /** Tags for the note, separated by spaces, added to the tags of the settings. */
+    const val EXTRA_TAGS = "space.subread.anki.extra.TAGS"
+    /** True: take a screenshot now when the capture service is on and no image came. */
+    const val EXTRA_SCREENSHOT = "space.subread.anki.extra.SCREENSHOT"
+    /** True: show the card before it is added, also when the settings say to add at once. */
+    const val EXTRA_SHOW = "space.subread.anki.extra.SHOW"
+    /** In the result of the activity: the id of the note in Anki. */
+    const val EXTRA_NOTE_ID = "space.subread.anki.extra.NOTE_ID"
+}
diff --git a/app/src/main/kotlin/space/subread/anki/Dictionary.kt b/app/src/main/kotlin/space/subread/anki/Dictionary.kt
new file mode 100644
index 0000000..31db65c
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/anki/Dictionary.kt
@@ -0,0 +1,86 @@
+package space.subread.anki
+
+import android.content.Context
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.os.Build
+import androidx.core.net.toUri
+import java.io.File
+
+/**
+ * Asks SubRead Dictionary for the definition and the audio of a word. The dictionary app has a
+ * content provider for this: `terms?text=` gives the terms at the start of a text, `audio?...`
+ * gives the first audio file that a source has.
+ */
+class Dictionary(private val context: Context) {
+
+    /** One term of one dictionary. [length] is how many characters of the text the term covers. */
+    data class Entry(val expression: String, val reading: String, val length: Int, val dictionary: String, val definition: String)
+
+    private val resolver get() = context.contentResolver
+
+    /** The authority of the installed dictionary app: the release one, else the debug one. Null without the app. */
+    private val authority: String?
+        get() = AUTHORITIES.firstOrNull { authority ->
+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+                context.packageManager.resolveContentProvider(authority, PackageManager.ComponentInfoFlags.of(0)) != null
+            } else {
+                @Suppress("DEPRECATION")
+                context.packageManager.resolveContentProvider(authority, 0) != null
+            }
+        }
+
+    val installed: Boolean get() = authority != null
+
+    private fun root(): Uri? = authority?.let { "content://$it".toUri() }
+
+    /** The terms at the start of the text, the longest first. Empty when nothing matches or the dictionary is away. */
+    fun lookup(text: String): List<Entry> = runCatching {
+        val terms = Uri.withAppendedPath(root() ?: return emptyList(), "terms")
+        val uri = terms.buildUpon().appendQueryParameter("text", text).build()
+        resolver.query(uri, null, null, null, null)?.use { c ->
+            buildList {
+                while (c.moveToNext()) {
+                    add(
+                        Entry(
+                            c.getString(c.getColumnIndexOrThrow("expression")),
+                            c.getString(c.getColumnIndexOrThrow("reading")),
+                            c.getInt(c.getColumnIndexOrThrow("length")),
+                            c.getString(c.getColumnIndexOrThrow("dictionary")),
+                            c.getString(c.getColumnIndexOrThrow("definition_html")),
+                        ),
+                    )
+                }
+            }
+        }
+    }.getOrNull().orEmpty()
+
+    /** The audio of a term, copied into the cache. Null when no source has it. */
+    fun audio(expression: String, reading: String): File? = runCatching {
+        val audio = Uri.withAppendedPath(root() ?: return null, "audio")
+        val uri = audio.buildUpon().appendQueryParameter("expression", expression).appendQueryParameter("reading", reading).build()
+        val name = resolver.query(uri, null, null, null, null)?.use { c ->
+            if (c.moveToFirst()) c.getString(c.getColumnIndexOrThrow("file")) else null
+        } ?: return null
+        val bytes = resolver.openInputStream(Uri.withAppendedPath(audio, name))?.use { it.readBytes() } ?: return null
+        if (bytes.isEmpty()) null else Media.write(context, bytes, "word", "audio")
+    }.getOrNull()
+
+    companion object {
+        const val PACKAGE = "space.subread.dictionary"
+        const val INSTALL = "https://github.com/equwal/subread-dictionary/releases/latest"
+
+        /** The provider of the dictionary app, and the one of its debug build. */
+        val AUTHORITIES = listOf("space.subread.dictionary.lookup", "space.subread.dictionary.debug.lookup")
+
+        /**
+         * The definition of the first term: the glossary of each dictionary that has that term
+         * with that reading, each under the name of its dictionary.
+         */
+        fun definition(entries: List<Entry>): String {
+            val first = entries.firstOrNull() ?: return ""
+            return entries.filter { it.expression == first.expression && it.reading == first.reading }
+                .joinToString("<br><br>") { "<i>${it.dictionary}</i><br>${it.definition}" }
+        }
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/anki/MainActivity.kt b/app/src/main/kotlin/space/subread/anki/MainActivity.kt
new file mode 100644
index 0000000..edd55b8
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/anki/MainActivity.kt
@@ -0,0 +1,321 @@
+package space.subread.anki
+
+import android.annotation.SuppressLint
+import android.app.Activity
+import android.app.AlertDialog
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.graphics.Color
+import android.graphics.Typeface
+import android.os.Bundle
+import android.provider.Settings
+import android.text.InputType
+import android.view.Gravity
+import android.view.View
+import android.widget.AdapterView
+import android.widget.ArrayAdapter
+import android.widget.Button
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.Spinner
+import android.widget.TextView
+import android.widget.Toast
+import androidx.core.net.toUri
+import space.subread.anki.core.Fields
+import space.subread.anki.core.NoteType
+import space.subread.anki.core.Slot
+import kotlin.concurrent.thread
+
+/**
+ * The settings, and the one screen that opens from the launcher: AnkiDroid with the deck, the
+ * note type and its fields; the capture service; the audio; the card; and a field to try it.
+ */
+class MainActivity : Activity() {
+
+    private lateinit var store: Store
+    private lateinit var anki: AnkiDroid
+    private lateinit var dictionary: Dictionary
+    private lateinit var content: LinearLayout
+
+    /** What AnkiDroid has, read off the main thread. Empty until it answers. */
+    private var decks: Map<Long, String> = emptyMap()
+    private var models: List<AnkiDroid.Model> = emptyList()
+
+    override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+        store = Store(this)
+        anki = AnkiDroid(this)
+        dictionary = Dictionary(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)
+        })
+    }
+
+    /** The user comes back from the settings of Android and from AnkiDroid here, so the state is read again. */
+    override fun onResume() {
+        super.onResume()
+        draw()
+        load()
+    }
+
+    private fun load() {
+        if (!anki.installed || !anki.permitted) return
+        thread(name = "anki") {
+            val result = runCatching { anki.decks() to anki.models() }
+            runOnUiThread {
+                result.onSuccess { (d, m) ->
+                    decks = d
+                    models = m
+                    draw()
+                }.onFailure { toast(getString(R.string.anki_error, it.message ?: it.javaClass.simpleName)) }
+            }
+        }
+    }
+
+    private fun draw() {
+        content.removeAllViews()
+        title(getString(R.string.app_name))
+        note(getString(R.string.about))
+        note(getString(R.string.privacy))
+
+        // 1. AnkiDroid
+        when {
+            !anki.installed -> step(R.string.step_anki, getString(R.string.anki_missing), getString(R.string.anki_get)) { open(AnkiDroid.INSTALL) }
+            !anki.permitted -> step(R.string.step_anki, getString(R.string.anki_permission), getString(R.string.allow)) {
+                requestPermissions(arrayOf(AnkiDroid.PERMISSION), PERMISSION)
+            }
+            else -> {
+                step(R.string.step_anki, "", null, done = true) {}
+                val deckName = decks[store.deckId] ?: getString(R.string.deck_default)
+                row(label(getString(R.string.deck, deckName)), button(getString(R.string.choose)) { chooseDeck() })
+                val model = models.firstOrNull { it.id == store.modelId }
+                row(label(getString(R.string.note_type, model?.name ?: getString(R.string.note_type_default))), button(getString(R.string.choose)) { chooseModel() })
+                note(getString(R.string.fields), top = 12, bold = true)
+                note(getString(R.string.fields_why), top = 2, color = Color.DKGRAY, size = 13f)
+                fieldRows(model)
+            }
+        }
+
+        // 2. Sentence and screenshot
+        val capture = Capture.isEnabled(this)
+        step(
+            R.string.step_capture,
+            getString(R.string.step_capture_why) + "\n\n" + getString(if (capture) R.string.capture_on else R.string.capture_off),
+            getString(R.string.capture_open),
+            done = capture,
+        ) { runCatching { startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)) } }
+        toggle(if (store.image) R.string.image_on else R.string.image_off, store.image) { store.image = it }
+
+        // 3. Audio
+        step(R.string.step_audio, "", null) {}
+        toggle(if (store.audio) R.string.audio_on else R.string.audio_off, store.audio) { store.audio = it }
+        toggle(if (store.sentenceAudio) R.string.sentence_audio_on else R.string.sentence_audio_off, store.sentenceAudio) { store.sentenceAudio = it }
+
+        // 4. The card
+        step(R.string.step_card, "", null) {}
+        toggle(if (store.dictionary) R.string.dictionary_on else R.string.dictionary_off, store.dictionary) { store.dictionary = it }
+        note(getString(if (store.addAtOnce) R.string.at_once_on else R.string.at_once_off), top = 12)
+        content.addView(button(getString(if (store.addAtOnce) R.string.at_once_show else R.string.at_once_add)) {
+            store.addAtOnce = !store.addAtOnce
+            draw()
+        }, LinearLayout.LayoutParams(-2, -2))
+        note(getString(R.string.tags), top = 12)
+        val tags = field(store.tags, single = true)
+        content.addView(button(getString(R.string.save)) {
+            store.tags = tags.text.toString()
+            toast(getString(R.string.saved))
+        }, LinearLayout.LayoutParams(-2, -2))
+
+        // 5. Try it
+        step(R.string.step_try, "", null) {}
+        val tryField = field("", single = false).apply { hint = getString(R.string.try_hint) }
+        content.addView(button(getString(R.string.try_add)) {
+            val text = tryField.text.toString().trim()
+            if (text.isEmpty()) return@button
+            val intent = Intent(this, AddActivity::class.java).setAction(Contract.ACTION_ADD).putExtra(Contract.EXTRA_SHOW, true)
+            if (text.any { it.isWhitespace() }) intent.putExtra(Contract.EXTRA_TEXT, text) else intent.putExtra(Contract.EXTRA_WORD, text)
+            startActivity(intent)
+        }, LinearLayout.LayoutParams(-2, -2))
+
+        // The other apps
+        note(getString(R.string.dictionary_note), top = 32)
+        val dictionaryApp = packageManager.getLaunchIntentForPackage(Dictionary.PACKAGE)
+        if (dictionaryApp != null) {
+            content.addView(button(getString(R.string.open_dictionary)) { runCatching { startActivity(dictionaryApp) } }, wide())
+        } else {
+            content.addView(button(getString(R.string.install_dictionary)) { open(Dictionary.INSTALL) }, wide())
+        }
+        if (BuildConfig.DONATE_LINK) content.addView(button(getString(R.string.donate)) { open(KOFI) }, wide())
+    }
+
+    /** One row per field of the note type: the name, and what goes into it. */
+    private fun fieldRows(model: AnkiDroid.Model?) {
+        val fields = model?.fields ?: NoteType.FIELDS
+        val stored = store.mapping
+        val mapping = if (fields.any { it in stored }) stored else if (model == null) NoteType.MAPPING else Fields.guessAll(fields)
+        val labels = Slot.entries.map { it.label }
+        for (name in fields) {
+            val spinner = Spinner(this).apply {
+                adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_dropdown_item, labels)
+                setSelection(Slot.entries.indexOf(mapping[name] ?: Slot.NONE))
+                onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
+                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
+                        val slot = Slot.entries[position]
+                        val now = store.mapping.toMutableMap()
+                        if (!fields.any { it in now }) now.putAll(mapping)
+                        if (now[name] != slot) {
+                            now[name] = slot
+                            store.mapping = now
+                        }
+                    }
+
+                    override fun onNothingSelected(parent: AdapterView<*>?) = Unit
+                }
+            }
+            content.addView(LinearLayout(this).apply {
+                gravity = Gravity.CENTER_VERTICAL
+                addView(label(name), LinearLayout.LayoutParams(0, -2, 1f))
+                addView(spinner, LinearLayout.LayoutParams(0, -2, 1.4f))
+            }, wide(2))
+        }
+    }
+
+    private fun chooseDeck() {
+        val list = decks.toList().sortedBy { it.second }
+        val names = list.map { it.second } + getString(R.string.new_deck)
+        AlertDialog.Builder(this).setItems(names.toTypedArray()) { _, which ->
+            if (which < list.size) {
+                store.deckId = list[which].first
+                store.deckName = list[which].second
+                draw()
+            } else {
+                newDeck()
+            }
+        }.show()
+    }
+
+    private fun newDeck() {
+        val name = EditText(this).apply { hint = getString(R.string.new_deck_name) }
+        AlertDialog.Builder(this).setView(name).setPositiveButton(android.R.string.ok) { _, _ ->
+            val value = name.text.toString().trim()
+            if (value.isEmpty()) return@setPositiveButton
+            thread {
+                val id = runCatching { anki.addDeck(value) }.getOrNull()
+                runOnUiThread {
+                    if (id == null) {
+                        toast(getString(R.string.error_deck))
+                    } else {
+                        store.deckId = id
+                        store.deckName = value
+                        load()
+                    }
+                }
+            }
+        }.setNegativeButton(android.R.string.cancel, null).show()
+    }
+
+    private fun chooseModel() {
+        val list = models.filter { it.fields.isNotEmpty() }.sortedBy { it.name }
+        val names = listOf(getString(R.string.note_type_default)) + list.map { "${it.name} (${it.fields.joinToString(", ")})" }
+        AlertDialog.Builder(this).setItems(names.toTypedArray()) { _, which ->
+            val model = list.getOrNull(which - 1)
+            store.modelId = model?.id ?: -1
+            store.modelName = model?.name ?: ""
+            store.mapping = if (model == null) emptyMap() else Fields.guessAll(model.fields)
+            draw()
+        }.show()
+    }
+
+    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
+        if (requestCode == PERMISSION && grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) {
+            draw()
+            load()
+        }
+    }
+
+    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, bold: Boolean = false) =
+        content.addView(TextView(this).apply {
+            text = value
+            textSize = size
+            setTextColor(color)
+            if (bold) setTypeface(typeface, Typeface.BOLD)
+        }, wide(top))
+
+    private fun label(value: String) = TextView(this).apply {
+        text = value
+        textSize = 15f
+        setTextColor(Color.BLACK)
+    }
+
+    private fun toggle(text: Int, on: Boolean, set: (Boolean) -> Unit) {
+        row(label(getString(text)), button(getString(if (on) R.string.turn_off else R.string.turn_on)) {
+            set(!on)
+            draw()
+        })
+    }
+
+    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?, done: Boolean = false, 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) + if (done) "  ✓ ${getString(R.string.anki_allowed)}" else ""
+            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(text: View, action: View) = content.addView(LinearLayout(this).apply {
+        gravity = Gravity.CENTER_VERTICAL
+        addView(text, LinearLayout.LayoutParams(0, -2, 1f))
+        addView(action, LinearLayout.LayoutParams(-2, -2))
+    }, wide(2))
+
+    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 PERMISSION = 1
+        const val KOFI = "https://ko-fi.com/truex"
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/anki/Media.kt b/app/src/main/kotlin/space/subread/anki/Media.kt
new file mode 100644
index 0000000..151092b
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/anki/Media.kt
@@ -0,0 +1,68 @@
+package space.subread.anki
+
+import android.content.Context
+import android.net.Uri
+import android.webkit.MimeTypeMap
+import androidx.core.content.FileProvider
+import java.io.File
+
+/** The files of a card on their way to AnkiDroid: in the cache, shared through the file provider. */
+object Media {
+
+    /** Files older than this go. A card takes seconds; an hour is safe. */
+    private const val KEEP_MS = 60 * 60_000L
+
+    fun dir(context: Context): File = File(context.cacheDir, "anki").apply { mkdirs() }
+
+    /** A fresh file name in the cache, with the extension. */
+    fun file(context: Context, stem: String, extension: String): File =
+        File(dir(context), "$stem-${System.nanoTime()}.$extension")
+
+    /** The URI that another app, AnkiDroid, reads the file through. */
+    fun uri(context: Context, file: File): Uri = FileProvider.getUriForFile(context, context.packageName + ".files", file)
+
+    /** Copies what a URI gives into the cache. Null when the URI cannot be read. */
+    fun copy(context: Context, source: Uri, stem: String, kind: String): File? = runCatching {
+        val bytes = context.contentResolver.openInputStream(source)!!.use { it.readBytes() }
+        if (bytes.isEmpty()) return null
+        val extension = extension(context, source) ?: sniff(bytes, kind)
+        file(context, stem, extension).also { it.writeBytes(bytes) }
+    }.getOrNull()
+
+    /** Writes bytes to the cache, with the extension that their format has. */
+    fun write(context: Context, bytes: ByteArray, stem: String, kind: String): File =
+        file(context, stem, sniff(bytes, kind)).also { it.writeBytes(bytes) }
+
+    /** The extension of the type that the provider of the URI reports, or of the name of the URI. */
+    private fun extension(context: Context, uri: Uri): String? {
+        val fromType = context.contentResolver.getType(uri)?.let { MimeTypeMap.getSingleton().getExtensionFromMimeType(it) }
+        if (fromType != null) return fromType
+        val name = uri.lastPathSegment ?: return null
+        return name.substringAfterLast('.', "").takeIf { it.length in 2..4 && it.all(Char::isLetterOrDigit) }?.lowercase()
+    }
+
+    /** The extension from the first bytes of a file. [kind] is "audio" or "image": the extension when the bytes say nothing. */
+    fun sniff(bytes: ByteArray, kind: String): String {
+        fun startsWith(prefix: String, at: Int = 0) = bytes.size >= at + prefix.length &&
+            prefix.indices.all { bytes[at + it] == prefix[it].code.toByte() }
+        return when {
+            startsWith("ID3") || (bytes.size > 1 && bytes[0] == 0xFF.toByte() && (bytes[1].toInt() and 0xE0) == 0xE0) -> "mp3"
+            startsWith("OggS") -> "ogg"
+            startsWith("RIFF") && startsWith("WAVE", 8) -> "wav"
+            startsWith("fLaC") -> "flac"
+            startsWith("ftyp", 4) -> "m4a"
+            bytes.size > 3 && bytes[0] == 0xFF.toByte() && bytes[1] == 0xD8.toByte() -> "jpg"
+            startsWith("\u0089PNG") -> "png"
+            startsWith("GIF8") -> "gif"
+            startsWith("RIFF") && startsWith("WEBP", 8) -> "webp"
+            kind == "image" -> "jpg"
+            else -> "mp3"
+        }
+    }
+
+    /** Deletes the old files of the cache. */
+    fun clean(context: Context) {
+        val limit = System.currentTimeMillis() - KEEP_MS
+        dir(context).listFiles()?.forEach { if (it.lastModified() < limit) it.delete() }
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/anki/Notes.kt b/app/src/main/kotlin/space/subread/anki/Notes.kt
new file mode 100644
index 0000000..f031f4e
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/anki/Notes.kt
@@ -0,0 +1,96 @@
+package space.subread.anki
+
+import android.content.Context
+import space.subread.anki.core.Card
+import space.subread.anki.core.Fields
+import space.subread.anki.core.NoteType
+import space.subread.anki.core.Slot
+import java.io.File
+
+/** A card with its files, before it goes to Anki. */
+class Draft(
+    var word: String = "",
+    /** The word as it stands in the sentence: 食べた for 食べる. */
+    var surface: String = "",
+    var reading: String = "",
+    var definition: String = "",
+    /** A text with no word chosen: the user taps the word in it. */
+    var text: String = "",
+    var sentence: space.subread.anki.core.Sentence? = null,
+    var image: File? = null,
+    var audio: File? = null,
+    var sentenceAudio: File? = null,
+    var source: String = "",
+    var url: String = "",
+    var tags: String = "",
+)
+
+/** What happened to a card. */
+data class Added(val noteId: Long, val word: String, val duplicates: Int)
+
+/** Sends a draft to AnkiDroid: the deck and the note type of the settings, the files, then the note. */
+class Notes(private val context: Context, private val store: Store, private val anki: AnkiDroid) {
+
+    /** The deck of the settings, or the "SubRead" deck, made when Anki has none. */
+    fun deck(): Pair<Long, String> {
+        val decks = anki.decks()
+        val chosen = store.deckId
+        decks[chosen]?.let { return chosen to it }
+        val id = decks.entries.firstOrNull { it.value == NoteType.NAME }?.key
+            ?: anki.addDeck(NoteType.NAME)
+            ?: throw IllegalStateException(context.getString(R.string.error_deck))
+        store.deckId = id
+        store.deckName = NoteType.NAME
+        return id to NoteType.NAME
+    }
+
+    /** The note type of the settings, or the "SubRead" note type, made when Anki has none. */
+    fun model(): AnkiDroid.Model {
+        val models = anki.models()
+        models.firstOrNull { it.id == store.modelId }?.let { return it }
+        val existing = models.firstOrNull { it.name == NoteType.NAME }
+        val model = existing ?: run {
+            anki.addModel(NoteType.NAME, NoteType.FIELDS, NoteType.CARD, NoteType.FRONT, NoteType.BACK, NoteType.CSS)
+            anki.models().firstOrNull { it.name == NoteType.NAME }
+        } ?: throw IllegalStateException(context.getString(R.string.error_model))
+        store.modelId = model.id
+        store.modelName = model.name
+        store.mapping = if (model.fields == NoteType.FIELDS) NoteType.MAPPING else Fields.guessAll(model.fields)
+        return model
+    }
+
+    /** The mapping of the settings for this note type; a guess from the field names when the settings have none for it. */
+    fun mapping(model: AnkiDroid.Model): Map<String, Slot> {
+        val stored = store.mapping
+        return if (model.fields.any { it in stored }) stored else Fields.guessAll(model.fields)
+    }
+
+    /** Puts the files in the media folder of Anki and adds the note. Throws with a message when a step fails. */
+    fun add(draft: Draft): Added {
+        val (deckId, _) = deck()
+        val model = model()
+        val mapping = mapping(model)
+        val card = Card(
+            word = draft.word,
+            reading = draft.reading,
+            definition = draft.definition,
+            sentence = draft.sentence,
+            image = media(draft.image, "subread-image"),
+            audio = media(draft.audio, "subread-word"),
+            sentenceAudio = media(draft.sentenceAudio, "subread-sentence"),
+            source = draft.source,
+            url = draft.url,
+        )
+        val fields = Fields.fill(card, model.fields, mapping)
+        if (fields.all { it.isEmpty() }) throw IllegalStateException(context.getString(R.string.error_empty))
+        val duplicates = anki.duplicates(model, fields[0])
+        val tags = (store.tags + " " + draft.tags).split(Regex("\\s+")).filter { it.isNotEmpty() }.toSet()
+        val noteId = anki.addNote(model.id, deckId, fields, tags) ?: throw IllegalStateException(context.getString(R.string.error_note))
+        return Added(noteId, draft.word, duplicates)
+    }
+
+    private fun media(file: File?, stem: String): String {
+        if (file == null || !file.isFile) return ""
+        return anki.addMedia(Media.uri(context, file), stem) ?: throw IllegalStateException(context.getString(R.string.error_media, file.name))
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/anki/Request.kt b/app/src/main/kotlin/space/subread/anki/Request.kt
new file mode 100644
index 0000000..78d3b1c
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/anki/Request.kt
@@ -0,0 +1,79 @@
+package space.subread.anki
+
+import android.content.Intent
+import android.net.Uri
+import androidx.core.content.IntentCompat
+import androidx.core.net.toUri
+
+/** What an intent asks for: the parts of the card that the sender knows. */
+data class Request(
+    val word: String = "",
+    val reading: String = "",
+    val definition: String = "",
+    val sentence: String = "",
+    val text: String = "",
+    val image: Uri? = null,
+    val audio: Uri? = null,
+    val sentenceAudio: Uri? = null,
+    val source: String = "",
+    val url: String = "",
+    val tags: String = "",
+    /** True: take a screenshot now when no image came and none is fresh. */
+    val screenshot: Boolean = false,
+    /** True: show the card before it goes to Anki. */
+    val show: Boolean = false,
+    /** The package of the app that sent the intent, when Android says. */
+    val caller: String? = null,
+) {
+    companion object {
+        /** A selected or shared text this short, with no space and no end mark, is the word itself. */
+        private const val WORD_MAX = 30
+        private const val NOT_IN_A_WORD = " \t\n。.!?!?、,.;:"
+
+        /** The request of the intent, or null when it brings nothing to make a card from. */
+        fun of(intent: Intent, caller: String?): Request? = when (intent.action) {
+            Intent.ACTION_PROCESS_TEXT -> {
+                val text = intent.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT)?.toString()?.trim().orEmpty()
+                if (text.isEmpty()) null else fromText(text, null, caller)
+            }
+            Intent.ACTION_SEND -> {
+                val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()?.trim().orEmpty()
+                val image = if (intent.type?.startsWith("image/") == true) IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java) else null
+                if (text.isEmpty()) null else fromText(text, image, caller)
+            }
+            Contract.ACTION_ADD -> {
+                fun text(name: String) = intent.getStringExtra(name)?.trim().orEmpty()
+                fun uri(name: String) = intent.getStringExtra(name)?.takeIf { it.isNotBlank() }?.toUri()
+                Request(
+                    word = text(Contract.EXTRA_WORD),
+                    reading = text(Contract.EXTRA_READING),
+                    definition = text(Contract.EXTRA_DEFINITION),
+                    sentence = text(Contract.EXTRA_SENTENCE),
+                    text = text(Contract.EXTRA_TEXT),
+                    image = uri(Contract.EXTRA_IMAGE),
+                    audio = uri(Contract.EXTRA_AUDIO),
+                    sentenceAudio = uri(Contract.EXTRA_SENTENCE_AUDIO),
+                    source = text(Contract.EXTRA_SOURCE),
+                    url = text(Contract.EXTRA_URL),
+                    tags = text(Contract.EXTRA_TAGS),
+                    screenshot = intent.getBooleanExtra(Contract.EXTRA_SCREENSHOT, false),
+                    show = intent.getBooleanExtra(Contract.EXTRA_SHOW, false),
+                    caller = caller,
+                ).takeIf { it.word.isNotEmpty() || it.text.isNotEmpty() }
+            }
+            else -> null
+        }
+
+        /** A short text with no space is the word. A longer one is a text: the user taps the word in it. */
+        private fun fromText(text: String, image: Uri?, caller: String?): Request {
+            val isWord = text.length <= WORD_MAX && text.none { it in NOT_IN_A_WORD }
+            return Request(
+                word = if (isWord) text else "",
+                text = if (isWord) "" else text,
+                image = image,
+                screenshot = true,
+                caller = caller,
+            )
+        }
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/anki/Speech.kt b/app/src/main/kotlin/space/subread/anki/Speech.kt
new file mode 100644
index 0000000..4d4000b
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/anki/Speech.kt
@@ -0,0 +1,53 @@
+package space.subread.anki
+
+import android.content.Context
+import android.os.Bundle
+import android.speech.tts.TextToSpeech
+import android.speech.tts.UtteranceProgressListener
+import java.io.File
+import java.util.Locale
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+
+/** The voice of the device reads a sentence into a file. */
+class Speech(private val context: Context) {
+
+    /**
+     * Writes the sentence as a wave file. Blocks until the voice is done: call it off the main
+     * thread. False when the device has no voice for the language, or the voice fails.
+     */
+    fun synthesize(text: String, file: File, japanese: Boolean, timeoutMs: Long = 20_000): Boolean {
+        val ready = CountDownLatch(1)
+        var started = false
+        val tts = TextToSpeech(context) { status ->
+            started = status == TextToSpeech.SUCCESS
+            ready.countDown()
+        }
+        try {
+            if (!ready.await(timeoutMs, TimeUnit.MILLISECONDS) || !started) return false
+            val language = tts.setLanguage(if (japanese) Locale.JAPANESE else Locale.getDefault())
+            if (language == TextToSpeech.LANG_MISSING_DATA || language == TextToSpeech.LANG_NOT_SUPPORTED) return false
+
+            val done = CountDownLatch(1)
+            var success = false
+            tts.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
+                override fun onStart(utteranceId: String?) = Unit
+
+                override fun onDone(utteranceId: String?) {
+                    success = true
+                    done.countDown()
+                }
+
+                @Deprecated("Deprecated in Java")
+                override fun onError(utteranceId: String?) = done.countDown()
+
+                override fun onError(utteranceId: String?, errorCode: Int) = done.countDown()
+            })
+            val queued = tts.synthesizeToFile(text, Bundle(), file, "subread-${System.nanoTime()}")
+            if (queued != TextToSpeech.SUCCESS || !done.await(timeoutMs, TimeUnit.MILLISECONDS)) return false
+            return success && file.length() > 0
+        } finally {
+            tts.shutdown()
+        }
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/anki/Store.kt b/app/src/main/kotlin/space/subread/anki/Store.kt
new file mode 100644
index 0000000..43d5717
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/anki/Store.kt
@@ -0,0 +1,70 @@
+package space.subread.anki
+
+import android.content.Context
+import androidx.core.content.edit
+import org.json.JSONObject
+import space.subread.anki.core.Slot
+
+/** What the user chose. It stays when the app stops. */
+class Store(context: Context) {
+
+    private val prefs = context.getSharedPreferences("anki", Context.MODE_PRIVATE)
+
+    /** The deck the cards go to. -1: none chosen yet; the app makes a "SubRead" deck. */
+    var deckId: Long
+        get() = prefs.getLong("deck_id", -1)
+        set(value) = prefs.edit { putLong("deck_id", value) }
+
+    var deckName: String
+        get() = prefs.getString("deck_name", "") ?: ""
+        set(value) = prefs.edit { putString("deck_name", value) }
+
+    /** The note type. -1: none chosen yet; the app makes the "SubRead" note type. */
+    var modelId: Long
+        get() = prefs.getLong("model_id", -1)
+        set(value) = prefs.edit { putLong("model_id", value) }
+
+    var modelName: String
+        get() = prefs.getString("model_name", "") ?: ""
+        set(value) = prefs.edit { putString("model_name", value) }
+
+    /** Which part of the card each field of the note type holds. Empty: guessed from the field names. */
+    var mapping: Map<String, Slot>
+        get() {
+            val json = runCatching { JSONObject(prefs.getString("mapping", "{}") ?: "{}") }.getOrElse { JSONObject() }
+            return json.keys().asSequence().associateWith { key ->
+                runCatching { Slot.valueOf(json.getString(key)) }.getOrDefault(Slot.NONE)
+            }
+        }
+        set(value) = prefs.edit { putString("mapping", JSONObject(value.mapValues { it.value.name }).toString()) }
+
+    /** True: a card with a word and a definition goes to Anki at once. False: the card shows first. */
+    var addAtOnce: Boolean
+        get() = prefs.getBoolean("add_at_once", true)
+        set(value) = prefs.edit { putBoolean("add_at_once", value) }
+
+    /** True: the screenshot of the capture service goes on the card. */
+    var image: Boolean
+        get() = prefs.getBoolean("image", true)
+        set(value) = prefs.edit { putBoolean("image", value) }
+
+    /** True: the word audio comes from SubRead Dictionary when the sender gave none. */
+    var audio: Boolean
+        get() = prefs.getBoolean("audio", true)
+        set(value) = prefs.edit { putBoolean("audio", value) }
+
+    /** True: the voice of the device reads the sentence into a file for the card. */
+    var sentenceAudio: Boolean
+        get() = prefs.getBoolean("sentence_audio", true)
+        set(value) = prefs.edit { putBoolean("sentence_audio", value) }
+
+    /** True: the definition comes from SubRead Dictionary when the sender gave none. */
+    var dictionary: Boolean
+        get() = prefs.getBoolean("dictionary", true)
+        set(value) = prefs.edit { putBoolean("dictionary", value) }
+
+    /** The tags of each note, separated by spaces. */
+    var tags: String
+        get() = prefs.getString("tags", "subread") ?: "subread"
+        set(value) = prefs.edit { putString("tags", value.trim()) }
+}
diff --git a/app/src/main/res/drawable/icon.xml b/app/src/main/res/drawable/icon.xml
new file mode 100644
index 0000000..0a61933
--- /dev/null
+++ b/app/src/main/res/drawable/icon.xml
@@ -0,0 +1,10 @@
+<?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" />
+    <!-- Two flash cards, one behind the other, and a plus sign on the front one. -->
+    <path android:fillColor="#111111" android:pathData="M30,18h58v58h-58z" />
+    <path android:fillColor="#FFFFFF" android:pathData="M34,22h50v50h-50z" />
+    <path android:fillColor="#111111" android:pathData="M18,32h58v58h-58z" />
+    <path android:fillColor="#FFFFFF" android:pathData="M44,52h6v-12h6v12h6v6h-6v12h-6v-12h-6z" />
+</vector>
diff --git a/app/src/main/res/drawable/sheet.xml b/app/src/main/res/drawable/sheet.xml
new file mode 100644
index 0000000..d763407
--- /dev/null
+++ b/app/src/main/res/drawable/sheet.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<shape xmlns:android="http://schemas.android.com/apk/res/android">
+    <solid android:color="#FFFFFF" />
+    <stroke android:width="2dp" android:color="#000000" />
+    <corners android:topLeftRadius="12dp" android:topRightRadius="12dp" />
+</shape>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..da66f7e
--- /dev/null
+++ b/app/src/main/res/values/strings.xml
@@ -0,0 +1,95 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="app_name">SubRead Anki</string>
+    <string name="add_label">Add to Anki</string>
+    <string name="capture_label">SubRead Anki: the sentence and a screenshot for a card</string>
+    <string name="capture_summary">Keeps the last text selection and a screenshot for the card.</string>
+    <string name="capture_description">SubRead Anki uses this service for one thing: when you select a text in an app, it keeps that text and takes a screenshot, so that the next card gets the sentence around the word and a picture of the screen. It reads nothing else, keeps only the last selection and the last screenshot, and sends nothing anywhere.</string>
+
+    <string name="about">One tap makes an Anki card: the word, its reading and definition, the sentence it is in, a screenshot, the word audio and the sentence audio. Select a word in any app and choose "Add to Anki" in the menu, share a text, or tap the Anki button in SubRead Dictionary or SubRead Overlay.</string>
+    <string name="privacy">The card goes to AnkiDroid on this device. Nothing leaves the device.</string>
+
+    <string name="step_anki">1. AnkiDroid</string>
+    <string name="anki_missing">AnkiDroid is not installed. The cards go into it.</string>
+    <string name="anki_get">Get AnkiDroid</string>
+    <string name="anki_permission">SubRead Anki needs the permission to write to the AnkiDroid database.</string>
+    <string name="anki_allowed">Allowed</string>
+    <string name="allow">Allow</string>
+    <string name="deck">Deck: %1$s</string>
+    <string name="deck_default">SubRead (made when needed)</string>
+    <string name="note_type">Note type: %1$s</string>
+    <string name="note_type_default">SubRead (made when needed)</string>
+    <string name="choose">Choose</string>
+    <string name="new_deck">New deck…</string>
+    <string name="new_deck_name">Name of the deck</string>
+    <string name="fields">Fields of the note type</string>
+    <string name="fields_why">What goes into each field. The guess comes from the names of the fields.</string>
+    <string name="anki_error">AnkiDroid did not answer: %1$s</string>
+
+    <string name="step_capture">2. Sentence and screenshot</string>
+    <string name="step_capture_why">With the accessibility service on, the app keeps the last text you select in another app and takes a screenshot at that moment. The card then gets the sentence around the word and the picture. Without the service, the sentence is the text you selected, and there is no picture.</string>
+    <string name="capture_on">The service is on.</string>
+    <string name="capture_off">The service is off.</string>
+    <string name="capture_open">Open the accessibility settings</string>
+    <string name="image_on">Screenshot on the card: on</string>
+    <string name="image_off">Screenshot on the card: off</string>
+
+    <string name="step_audio">3. Audio</string>
+    <string name="audio_on">Word audio from SubRead Dictionary: on</string>
+    <string name="audio_off">Word audio from SubRead Dictionary: off</string>
+    <string name="sentence_audio_on">Sentence audio from the voice of the device: on</string>
+    <string name="sentence_audio_off">Sentence audio from the voice of the device: off</string>
+    <string name="turn_on">Turn on</string>
+    <string name="turn_off">Turn off</string>
+
+    <string name="step_card">4. The card</string>
+    <string name="dictionary_on">Definition from SubRead Dictionary: on</string>
+    <string name="dictionary_off">Definition from SubRead Dictionary: off</string>
+    <string name="at_once_on">Add at once: a word with a definition goes to Anki without a question.</string>
+    <string name="at_once_off">Show the card first: each card waits for the Add button.</string>
+    <string name="at_once_show">Show the card first</string>
+    <string name="at_once_add">Add at once</string>
+    <string name="tags">Tags, separated by spaces</string>
+    <string name="save">Save</string>
+    <string name="saved">Saved.</string>
+
+    <string name="step_try">5. Try it</string>
+    <string name="try_hint">A word, or a sentence</string>
+    <string name="try_add">Make a card</string>
+
+    <string name="dictionary_note">SubRead Dictionary gives the definition, the reading and the word audio. It reads Yomitan dictionaries.</string>
+    <string name="open_dictionary">Open SubRead Dictionary</string>
+    <string name="install_dictionary">Install SubRead Dictionary</string>
+    <string name="donate">Support the app on Ko-fi</string>
+
+    <string name="sheet_title">Add to Anki</string>
+    <string name="settings">Settings</string>
+    <string name="close">Close</string>
+    <string name="cancel">Cancel</string>
+    <string name="add">Add to Anki</string>
+    <string name="adding">Adding…</string>
+    <string name="word">Word</string>
+    <string name="reading">Reading</string>
+    <string name="definition">Definition</string>
+    <string name="no_definition">No definition. Install SubRead Dictionary and import a dictionary, or type one here.</string>
+    <string name="no_definition_found">No entry for this word in SubRead Dictionary.</string>
+    <string name="pick_word">Tap the word in the text.</string>
+    <string name="sentence">Sentence</string>
+    <string name="image">Screenshot</string>
+    <string name="image_none">No screenshot.</string>
+    <string name="remove">Remove</string>
+    <string name="word_audio">Word audio</string>
+    <string name="sentence_audio">Sentence audio</string>
+    <string name="tags_short">Tags</string>
+    <string name="no_text">The text is empty.</string>
+    <string name="no_word">Type the word first.</string>
+    <string name="added">Added to Anki: %1$s</string>
+    <string name="added_again">Added to Anki: %1$s (already there: %2$d)</string>
+    <string name="permission_denied">Without the permission, no card can go to AnkiDroid.</string>
+
+    <string name="error_deck">The deck could not be made.</string>
+    <string name="error_model">The note type could not be made.</string>
+    <string name="error_empty">Every field of the note is empty. Check the fields in the settings.</string>
+    <string name="error_note">AnkiDroid did not take the note.</string>
+    <string name="error_media">AnkiDroid did not take the file %1$s.</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..08c08cc
--- /dev/null
+++ b/app/src/main/res/values/styles.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <!-- The card sheet: see-through over the app that sent the word, so a screenshot shows that app. -->
+    <style name="Sheet" parent="@android:style/Theme.DeviceDefault.Light.NoActionBar">
+        <item name="android:windowIsTranslucent">true</item>
+        <item name="android:windowBackground">@android:color/transparent</item>
+        <item name="android:windowNoTitle">true</item>
+        <item name="android:windowAnimationStyle">@null</item>
+        <item name="android:backgroundDimEnabled">false</item>
+        <item name="android:windowContentOverlay">@null</item>
+    </style>
+</resources>
diff --git a/app/src/main/res/xml/capture.xml b/app/src/main/res/xml/capture.xml
new file mode 100644
index 0000000..9da5889
--- /dev/null
+++ b/app/src/main/res/xml/capture.xml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+    The capture service. It gets two kinds of events: a text selection changed in an app, and a
+    window came to the front. It can take a screenshot. It reads no other content.
+-->
+<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
+    android:accessibilityEventTypes="typeViewTextSelectionChanged|typeWindowStateChanged"
+    android:accessibilityFeedbackType="feedbackGeneric"
+    android:accessibilityFlags="flagDefault"
+    android:canRetrieveWindowContent="true"
+    android:canTakeScreenshot="true"
+    android:description="@string/capture_description"
+    android:notificationTimeout="50"
+    android:summary="@string/capture_summary" />
diff --git a/app/src/main/res/xml/files.xml b/app/src/main/res/xml/files.xml
new file mode 100644
index 0000000..a3ffc5d
--- /dev/null
+++ b/app/src/main/res/xml/files.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- The media of a card, on the way to AnkiDroid. -->
+<paths>
+    <cache-path name="anki" path="anki/" />
+</paths>
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..adba768
--- /dev/null
+++ b/core/build.gradle.kts
@@ -0,0 +1,30 @@
+import org.jetbrains.kotlin.gradle.dsl.JvmTarget
+
+plugins {
+    alias(libs.plugins.kotlin.jvm)
+}
+
+// Plain JVM on purpose: no Android types in here, so the sentence cut and the furigana can be tested on a laptop.
+java {
+    sourceCompatibility = JavaVersion.VERSION_17
+    targetCompatibility = JavaVersion.VERSION_17
+}
+kotlin {
+    compilerOptions { jvmTarget.set(JvmTarget.JVM_17) }
+}
+
+dependencies {
+
+    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/anki/core/Card.kt b/core/src/main/kotlin/space/subread/anki/core/Card.kt
new file mode 100644
index 0000000..cb91353
--- /dev/null
+++ b/core/src/main/kotlin/space/subread/anki/core/Card.kt
@@ -0,0 +1,114 @@
+package space.subread.anki.core
+
+/**
+ * What goes on a card. The media are the names of the files in the media folder of Anki,
+ * empty when the card has none. The definition is HTML.
+ */
+data class Card(
+    val word: String,
+    val reading: String = "",
+    val definition: String = "",
+    val sentence: Sentence? = null,
+    val image: String = "",
+    val audio: String = "",
+    val sentenceAudio: String = "",
+    val source: String = "",
+    val url: String = "",
+)
+
+/** What a field of a note type can hold. The user maps each field to one slot. */
+enum class Slot(val label: String) {
+    NONE("Nothing"),
+    WORD("Word"),
+    READING("Reading"),
+    FURIGANA("Word with furigana"),
+    DEFINITION("Definition"),
+    DEFINITION_TEXT("Definition as plain text"),
+    SENTENCE("Sentence"),
+    SENTENCE_BOLD("Sentence, the word in bold"),
+    SENTENCE_CLOZE("Sentence, the word as a cloze"),
+    IMAGE("Image"),
+    AUDIO("Word audio"),
+    SENTENCE_AUDIO("Sentence audio"),
+    SOURCE("Source"),
+    URL("Link"),
+}
+
+object Fields {
+
+    /** The value of a field that holds [slot], as Anki stores it: HTML. */
+    fun render(card: Card, slot: Slot): String = when (slot) {
+        Slot.NONE -> ""
+        Slot.WORD -> Html.escape(card.word)
+        Slot.READING -> Html.escape(card.reading)
+        Slot.FURIGANA -> Html.escape(Furigana.bracket(card.word, card.reading))
+        Slot.DEFINITION -> card.definition
+        Slot.DEFINITION_TEXT -> Html.escape(Html.text(card.definition))
+        Slot.SENTENCE -> card.sentence?.let { Html.escape(it.text) } ?: ""
+        Slot.SENTENCE_BOLD -> card.sentence?.let(Html::bold) ?: ""
+        Slot.SENTENCE_CLOZE -> card.sentence?.let(Html::cloze) ?: ""
+        Slot.IMAGE -> if (card.image.isEmpty()) "" else "<img src=\"${Html.escape(card.image)}\">"
+        Slot.AUDIO -> sound(card.audio)
+        Slot.SENTENCE_AUDIO -> sound(card.sentenceAudio)
+        Slot.SOURCE -> Html.escape(card.source)
+        Slot.URL -> if (card.url.isEmpty()) "" else "<a href=\"${Html.escape(card.url)}\">${Html.escape(card.url)}</a>"
+    }
+
+    /** The fields of a note type in their order, each rendered from its slot. A field with no slot is empty. */
+    fun fill(card: Card, fieldNames: List<String>, mapping: Map<String, Slot>): List<String> =
+        fieldNames.map { render(card, mapping[it] ?: Slot.NONE) }
+
+    private fun sound(name: String) = if (name.isEmpty()) "" else "[sound:$name]"
+
+    /** The slot that a field with this name most likely wants, from the words in the name. */
+    fun guess(fieldName: String): Slot {
+        val n = fieldName.lowercase().replace(Regex("[^a-z0-9\\p{IsHiragana}\\p{IsKatakana}\\p{IsHan}]"), "")
+        return when {
+            n.contains("sentenceaudio") || n.contains("contextaudio") || n.contains("audiosentence") -> Slot.SENTENCE_AUDIO
+            n.contains("audio") || n.contains("sound") || n.contains("音声") -> Slot.AUDIO
+            n.contains("furigana") || n.contains("ふりがな") -> Slot.FURIGANA
+            n.contains("reading") || n.contains("読み") || n.contains("よみ") || n.contains("kana") || n.contains("pronunciation") -> Slot.READING
+            n.contains("sentence") || n.contains("context") || n.contains("example") || n.contains("文") -> Slot.SENTENCE_BOLD
+            n.contains("image") || n.contains("picture") || n.contains("screenshot") || n.contains("画像") -> Slot.IMAGE
+            n.contains("definition") || n.contains("meaning") || n.contains("glossary") || n.contains("意味") || n == "back" -> Slot.DEFINITION
+            n.contains("source") || n.contains("出典") -> Slot.SOURCE
+            n.contains("url") || n.contains("link") -> Slot.URL
+            n.contains("word") || n.contains("expression") || n.contains("単語") || n.contains("term") || n.contains("vocab") || n == "front" -> Slot.WORD
+            else -> Slot.NONE
+        }
+    }
+
+    /** A mapping for the fields of a note type. A slot goes to the first field that wants it. */
+    fun guessAll(fieldNames: List<String>): Map<String, Slot> {
+        val taken = HashSet<Slot>()
+        return fieldNames.associateWith { name ->
+            val slot = guess(name)
+            if (slot == Slot.NONE || !taken.add(slot)) Slot.NONE else slot
+        }
+    }
+}
+
+/** The note type that the app makes in Anki when the user picks none. */
+object NoteType {
+    const val NAME = "SubRead"
+    val FIELDS = listOf("Word", "Reading", "Definition", "Sentence", "Image", "Audio", "SentenceAudio", "Source")
+    const val CARD = "Card 1"
+    const val FRONT = "<div class=\"word\">{{Word}}</div>\n<div class=\"sentence\">{{Sentence}}</div>"
+    const val BACK = "{{FrontSide}}\n<hr id=\"answer\">\n<div class=\"reading\">{{Reading}}</div>\n{{Audio}}\n" +
+        "<div class=\"definition\">{{Definition}}</div>\n<div class=\"image\">{{Image}}</div>\n{{SentenceAudio}}\n" +
+        "<div class=\"source\">{{Source}}</div>"
+    const val CSS = ".card { font-family: sans-serif; font-size: 22px; text-align: center; color: black; background-color: white; }\n" +
+        ".word { font-size: 40px; }\n.sentence { margin-top: 12px; }\n.sentence b { color: #b3261e; }\n" +
+        ".reading { color: #444; }\n.definition { margin-top: 12px; text-align: left; }\n" +
+        ".image img { max-width: 100%; max-height: 60vh; margin-top: 12px; }\n.source { margin-top: 12px; color: #888; font-size: 14px; }"
+    val MAPPING: Map<String, Slot> = mapOf(
+        "Word" to Slot.WORD,
+        "Reading" to Slot.READING,
+        "Definition" to Slot.DEFINITION,
+        "Sentence" to Slot.SENTENCE_BOLD,
+        "Image" to Slot.IMAGE,
+        "Audio" to Slot.AUDIO,
+        "SentenceAudio" to Slot.SENTENCE_AUDIO,
+        "Source" to Slot.SOURCE,
+    )
+}
diff --git a/core/src/main/kotlin/space/subread/anki/core/Furigana.kt b/core/src/main/kotlin/space/subread/anki/core/Furigana.kt
new file mode 100644
index 0000000..e505102
--- /dev/null
+++ b/core/src/main/kotlin/space/subread/anki/core/Furigana.kt
@@ -0,0 +1,62 @@
+package space.subread.anki.core
+
+/**
+ * Writes a word with its reading the way the furigana filter of Anki reads it: `食[た]べる`,
+ * `日本語[にほんご]`, `食[た]べ 物[もの]`. The kana of the word stay outside the brackets. Each run
+ * of kanji gets the part of the reading that is its own. A space separates a bracket group from
+ * the text before it; Anki does not show the space.
+ */
+object Furigana {
+
+    fun bracket(word: String, reading: String): String {
+        if (reading.isEmpty() || word.isEmpty()) return word
+        val kana = Kana.toHiragana(reading)
+        if (Kana.toHiragana(word) == kana || word.none(Kana::isKanji)) return word
+        return align(word, reading, kana) ?: "$word[$reading]"
+    }
+
+    /**
+     * The runs of the word, kanji and not kanji, in order. Each kana run must be in the reading
+     * at its place; the reading of a kanji run goes up to the next kana run of the word. Null
+     * when the reading does not fit the word.
+     */
+    private fun align(word: String, reading: String, kana: String): String? {
+        val runs = runs(word)
+        val out = StringBuilder()
+        var at = 0
+        for ((i, run) in runs.withIndex()) {
+            val (text, kanji) = run
+            if (!kanji) {
+                if (!kana.startsWith(Kana.toHiragana(text), at)) return null
+                out.append(text)
+                at += text.length
+                continue
+            }
+            val stop = if (i == runs.lastIndex) {
+                kana.length
+            } else {
+                // A kanji reads as one kana at least, so the next run starts after this one.
+                val found = kana.indexOf(Kana.toHiragana(runs[i + 1].first), at + 1)
+                if (found < 0) return null
+                found
+            }
+            if (stop <= at) return null
+            if (out.isNotEmpty()) out.append(' ')
+            out.append(text).append('[').append(reading, at, stop).append(']')
+            at = stop
+        }
+        return if (at == kana.length) out.toString() else null
+    }
+
+    private fun runs(word: String): List<Pair<String, Boolean>> {
+        val out = ArrayList<Pair<String, Boolean>>()
+        var start = 0
+        for (i in 1..word.length) {
+            if (i == word.length || Kana.isKanji(word[i]) != Kana.isKanji(word[start])) {
+                out.add(word.substring(start, i) to Kana.isKanji(word[start]))
+                start = i
+            }
+        }
+        return out
+    }
+}
diff --git a/core/src/main/kotlin/space/subread/anki/core/Html.kt b/core/src/main/kotlin/space/subread/anki/core/Html.kt
new file mode 100644
index 0000000..9a861d6
--- /dev/null
+++ b/core/src/main/kotlin/space/subread/anki/core/Html.kt
@@ -0,0 +1,39 @@
+package space.subread.anki.core
+
+/** The little HTML that a field of a note needs. */
+object Html {
+
+    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)
+        }
+    }
+
+    /** The sentence with the word in bold. */
+    fun bold(sentence: Sentence): String =
+        if (sentence.word.isEmpty()) escape(sentence.text)
+        else escape(sentence.before) + "<b>" + escape(sentence.word) + "</b>" + escape(sentence.after)
+
+    /** The sentence with the word as the first cloze. */
+    fun cloze(sentence: Sentence): String =
+        if (sentence.word.isEmpty()) escape(sentence.text)
+        else escape(sentence.before) + "{{c1::" + escape(sentence.word) + "}}" + escape(sentence.after)
+
+    /** The text of simple HTML: the tags go, a line break becomes a new line, the entities become characters. */
+    fun text(html: String): String = html
+        .replace(Regex("<br\\s*/?>", RegexOption.IGNORE_CASE), "\n")
+        .replace(Regex("</(p|div|li|tr)>", RegexOption.IGNORE_CASE), "\n")
+        .replace(Regex("<[^>]+>"), "")
+        .replace("&nbsp;", " ")
+        .replace("&lt;", "<")
+        .replace("&gt;", ">")
+        .replace("&quot;", "\"")
+        .replace("&#39;", "'")
+        .replace("&amp;", "&")
+        .replace(Regex("[ \t]*\n[ \t\n]*"), "\n")
+        .trim()
+}
diff --git a/core/src/main/kotlin/space/subread/anki/core/Kana.kt b/core/src/main/kotlin/space/subread/anki/core/Kana.kt
new file mode 100644
index 0000000..e509afc
--- /dev/null
+++ b/core/src/main/kotlin/space/subread/anki/core/Kana.kt
@@ -0,0 +1,22 @@
+package space.subread.anki.core
+
+/** Script checks. A reading is hiragana; a word can have the same sounds 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 isKanji(c: Char) = c in '一'..'鿿' || c in '㐀'..'䶿' || c == '々' || c == '〆' || c == '〇'
+
+    fun isJapanese(c: Char) = isKana(c) || isKanji(c)
+
+    fun hasJapanese(text: CharSequence) = text.any(::isJapanese)
+
+    /** Katakana to hiragana. Other characters stay. The result has the length of the text. */
+    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/anki/core/Sentences.kt b/core/src/main/kotlin/space/subread/anki/core/Sentences.kt
new file mode 100644
index 0000000..6bba810
--- /dev/null
+++ b/core/src/main/kotlin/space/subread/anki/core/Sentences.kt
@@ -0,0 +1,88 @@
+package space.subread.anki.core
+
+/**
+ * A sentence cut out of a longer text, with the place of the word in it.
+ *
+ * @param wordStart the index of the first character of the word in [text].
+ * @param wordEnd the index after the last character of the word in [text].
+ */
+data class Sentence(val text: String, val wordStart: Int, val wordEnd: Int) {
+
+    val word: String get() = text.substring(wordStart, wordEnd)
+
+    val before: String get() = text.substring(0, wordStart)
+
+    val after: String get() = text.substring(wordEnd)
+
+    companion object {
+        /** A sentence that is the word alone. */
+        fun of(word: String) = Sentence(word, 0, word.length)
+    }
+}
+
+/** Cuts the sentence around a word out of the text of a screen, a page or a subtitle file. */
+object Sentences {
+
+    /** Characters that end a sentence. A full stop ends one only before a space or at the end. */
+    private const val ENDS = "。.!?!?\n\r"
+
+    /** An end mark between an opener and its closer ends a quoted sentence, not the sentence around it. */
+    private const val OPENERS = "「『((【〔[[“‘"
+    private const val CLOSERS = "」』))】〕]]”’"
+
+    /** The most characters kept on each side of the word when no end is near it. */
+    const val MAX_SIDE = 120
+
+    /**
+     * The sentence of [text] that has the characters from [start] to [end]. The cut goes from
+     * the end mark before the word to the end mark after it, with the closing quote or bracket
+     * that follows that mark. Spaces at the two ends are dropped.
+     */
+    fun around(text: String, start: Int, end: Int): Sentence {
+        val wordStart = start.coerceIn(0, text.length)
+        val wordEnd = end.coerceIn(wordStart, text.length)
+
+        var from = 0
+        var depth = 0
+        for (i in wordStart - 1 downTo 0) {
+            val c = text[i]
+            when {
+                c in CLOSERS -> depth++
+                c in OPENERS -> depth = maxOf(0, depth - 1)
+                depth == 0 && isEnd(text, i) -> {
+                    from = i + 1
+                    break
+                }
+            }
+        }
+        // The closers after the end mark before the word belong to the sentence before.
+        while (from < wordStart && text[from] in CLOSERS) from++
+        if (from < wordStart - MAX_SIDE) from = wordStart - MAX_SIDE
+
+        var to = text.length
+        depth = 0
+        for (i in wordEnd until text.length) {
+            val c = text[i]
+            when {
+                c in OPENERS -> depth++
+                c in CLOSERS -> depth = maxOf(0, depth - 1)
+                depth == 0 && isEnd(text, i) -> {
+                    to = if (c == '\n' || c == '\r') i else i + 1
+                    while (to < text.length && text[to] in CLOSERS) to++
+                    break
+                }
+            }
+        }
+        if (to > wordEnd + MAX_SIDE) to = wordEnd + MAX_SIDE
+
+        while (from < wordStart && text[from].isWhitespace()) from++
+        while (to > wordEnd && text[to - 1].isWhitespace()) to--
+        return Sentence(text.substring(from, to), wordStart - from, wordEnd - from)
+    }
+
+    internal fun isEnd(text: String, at: Int): Boolean {
+        val c = text[at]
+        if (c in ENDS) return true
+        return c == '.' && (at + 1 == text.length || text[at + 1].isWhitespace())
+    }
+}
diff --git a/core/src/test/kotlin/space/subread/anki/core/CardTest.kt b/core/src/test/kotlin/space/subread/anki/core/CardTest.kt
new file mode 100644
index 0000000..bcd560d
--- /dev/null
+++ b/core/src/test/kotlin/space/subread/anki/core/CardTest.kt
@@ -0,0 +1,87 @@
+package space.subread.anki.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class CardTest {
+
+    private val card = Card(
+        word = "食べる",
+        reading = "たべる",
+        definition = "<i>Jitendex</i><br>to eat",
+        sentence = Sentences.around("パンを食べる。", 3, 6),
+        image = "subread-1.jpg",
+        audio = "subread-1.mp3",
+        sentenceAudio = "subread-1-sentence.wav",
+        source = "Voice & <VLC>",
+        url = "https://example.com/?a=1&b=2",
+    )
+
+    @Test
+    fun eachSlotRendersItsPart() {
+        assertEquals("食べる", Fields.render(card, Slot.WORD))
+        assertEquals("たべる", Fields.render(card, Slot.READING))
+        assertEquals("食[た]べる", Fields.render(card, Slot.FURIGANA))
+        assertEquals("<i>Jitendex</i><br>to eat", Fields.render(card, Slot.DEFINITION))
+        assertEquals("Jitendex\nto eat", Fields.render(card, Slot.DEFINITION_TEXT))
+        assertEquals("パンを食べる。", Fields.render(card, Slot.SENTENCE))
+        assertEquals("パンを<b>食べる</b>。", Fields.render(card, Slot.SENTENCE_BOLD))
+        assertEquals("パンを{{c1::食べる}}。", Fields.render(card, Slot.SENTENCE_CLOZE))
+        assertEquals("<img src=\"subread-1.jpg\">", Fields.render(card, Slot.IMAGE))
+        assertEquals("[sound:subread-1.mp3]", Fields.render(card, Slot.AUDIO))
+        assertEquals("[sound:subread-1-sentence.wav]", Fields.render(card, Slot.SENTENCE_AUDIO))
+        assertEquals("Voice &amp; &lt;VLC&gt;", Fields.render(card, Slot.SOURCE))
+        assertEquals(
+            "<a href=\"https://example.com/?a=1&amp;b=2\">https://example.com/?a=1&amp;b=2</a>",
+            Fields.render(card, Slot.URL),
+        )
+        assertEquals("", Fields.render(card, Slot.NONE))
+    }
+
+    @Test
+    fun anEmptyPartRendersEmpty() {
+        val bare = Card("食べる")
+        for (slot in Slot.entries) if (slot != Slot.WORD && slot != Slot.FURIGANA) assertEquals(slot.name, "", Fields.render(bare, slot))
+        assertEquals("食べる", Fields.render(bare, Slot.FURIGANA))
+    }
+
+    @Test
+    fun theFieldsOfANoteTypeFillInOrder() {
+        val fields = listOf("Front", "Back", "Extra")
+        val mapping = mapOf("Front" to Slot.WORD, "Back" to Slot.DEFINITION)
+        assertEquals(listOf("食べる", "<i>Jitendex</i><br>to eat", ""), Fields.fill(card, fields, mapping))
+    }
+
+    @Test
+    fun aFieldNameSaysWhatItWants() {
+        assertEquals(Slot.WORD, Fields.guess("Expression"))
+        assertEquals(Slot.WORD, Fields.guess("Front"))
+        assertEquals(Slot.READING, Fields.guess("Reading"))
+        assertEquals(Slot.FURIGANA, Fields.guess("Furigana"))
+        assertEquals(Slot.DEFINITION, Fields.guess("Meaning"))
+        assertEquals(Slot.DEFINITION, Fields.guess("Back"))
+        assertEquals(Slot.SENTENCE_BOLD, Fields.guess("Sentence"))
+        assertEquals(Slot.SENTENCE_BOLD, Fields.guess("例文"))
+        assertEquals(Slot.IMAGE, Fields.guess("Picture"))
+        assertEquals(Slot.AUDIO, Fields.guess("Word Audio"))
+        assertEquals(Slot.SENTENCE_AUDIO, Fields.guess("Sentence Audio"))
+        assertEquals(Slot.SOURCE, Fields.guess("Source"))
+        assertEquals(Slot.URL, Fields.guess("URL"))
+        assertEquals(Slot.NONE, Fields.guess("Notes"))
+    }
+
+    @Test
+    fun aSlotGoesToTheFirstFieldThatWantsIt() {
+        assertEquals(
+            mapOf("Word" to Slot.WORD, "Word 2" to Slot.NONE, "Back" to Slot.DEFINITION),
+            Fields.guessAll(listOf("Word", "Word 2", "Back")),
+        )
+        assertEquals(NoteType.MAPPING, Fields.guessAll(NoteType.FIELDS))
+    }
+
+    @Test
+    fun htmlBecomesText() {
+        assertEquals("a < b\nc & d", Html.text("<p>a &lt; b</p><br>c &amp; d"))
+        assertEquals("one\ntwo", Html.text("<ul><li>one</li><li>two</li></ul>"))
+    }
+}
diff --git a/core/src/test/kotlin/space/subread/anki/core/FuriganaTest.kt b/core/src/test/kotlin/space/subread/anki/core/FuriganaTest.kt
new file mode 100644
index 0000000..6a20218
--- /dev/null
+++ b/core/src/test/kotlin/space/subread/anki/core/FuriganaTest.kt
@@ -0,0 +1,61 @@
+package space.subread.anki.core
+
+import io.kotest.property.Arb
+import io.kotest.property.arbitrary.element
+import io.kotest.property.arbitrary.filter
+import io.kotest.property.arbitrary.list
+import io.kotest.property.arbitrary.map
+import io.kotest.property.checkAll
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class FuriganaTest {
+
+    @Test
+    fun theKanaOfTheWordStayOutsideTheBrackets() {
+        assertEquals("食[た]べる", Furigana.bracket("食べる", "たべる"))
+        assertEquals("日本語[にほんご]", Furigana.bracket("日本語", "にほんご"))
+        assertEquals("食[た]べ 物[もの]", Furigana.bracket("食べ物", "たべもの"))
+        assertEquals("引[ひ]っ 越[こ]す", Furigana.bracket("引っ越す", "ひっこす"))
+        assertEquals("見[み]に 行[い]く", Furigana.bracket("見に行く", "みにいく"))
+        assertEquals("お 茶[ちゃ]", Furigana.bracket("お茶", "おちゃ"))
+        assertEquals("取[と]り 扱[あつか]い", Furigana.bracket("取り扱い", "とりあつかい"))
+        assertEquals("思[おも]い 出[で]", Furigana.bracket("思い出", "おもいで"))
+        assertEquals("生[い]き 生[い]き", Furigana.bracket("生き生き", "いきいき"))
+    }
+
+    @Test
+    fun aWordWithNoKanjiIsItself() {
+        assertEquals("たべる", Furigana.bracket("たべる", "たべる"))
+        assertEquals("コーヒー", Furigana.bracket("コーヒー", "こーひー"))
+        assertEquals("サボる", Furigana.bracket("サボる", "さぼる"))
+        assertEquals("食べる", Furigana.bracket("食べる", ""))
+    }
+
+    @Test
+    fun aReadingThatDoesNotFitGoesOnTheWholeWord() {
+        assertEquals("食べる[のむ]", Furigana.bracket("食べる", "のむ"))
+        assertEquals("3人[さんにん]", Furigana.bracket("3人", "さんにん"))
+        assertEquals("食べる[たべ]", Furigana.bracket("食べる", "たべ"))
+    }
+
+    @Test
+    fun theWordAndTheReadingComeBackOutOfTheBrackets() = runBlocking<Unit> {
+        val kanji = "食日本語物人見行".toList()
+        val kana = "たべものにほんごひっこすみいくおちゃ".toList()
+        val words = Arb.list(Arb.element(kanji + kana), 1..6).map { it.joinToString("") }.filter { it.any(Kana::isKanji) }
+        val readings = Arb.list(Arb.element(kana), 1..8).map { it.joinToString("") }
+        checkAll(words, readings) { word, reading ->
+            val out = Furigana.bracket(word, reading)
+            assertEquals(word, out.replace(Regex("\\[[^\\]]*\\]"), "").replace(" ", ""))
+            assertEquals(reading, readingOf(out))
+        }
+    }
+
+    /** Reads the furigana text back: each bracket group is the reading of the kanji before it. */
+    private fun readingOf(furigana: String): String = furigana.split(' ').joinToString("") { part ->
+        val open = part.indexOf('[')
+        if (open < 0) part else part.substring(open + 1, part.indexOf(']')) + part.substring(part.indexOf(']') + 1)
+    }
+}
diff --git a/core/src/test/kotlin/space/subread/anki/core/SentencesTest.kt b/core/src/test/kotlin/space/subread/anki/core/SentencesTest.kt
new file mode 100644
index 0000000..65a5821
--- /dev/null
+++ b/core/src/test/kotlin/space/subread/anki/core/SentencesTest.kt
@@ -0,0 +1,93 @@
+package space.subread.anki.core
+
+import io.kotest.property.Arb
+import io.kotest.property.arbitrary.element
+import io.kotest.property.arbitrary.int
+import io.kotest.property.arbitrary.list
+import io.kotest.property.arbitrary.map
+import io.kotest.property.checkAll
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class SentencesTest {
+
+    private fun cut(text: String, word: String): Sentence {
+        val at = text.indexOf(word)
+        assertTrue("the text has the word", at >= 0)
+        return Sentences.around(text, at, at + word.length)
+    }
+
+    @Test
+    fun theSentenceGoesFromTheEndMarkBeforeToTheEndMarkAfter() {
+        val s = cut("今日は天気がいい。明日は雨だ。また晴れる。", "明日")
+        assertEquals("明日は雨だ。", s.text)
+        assertEquals("明日", s.word)
+        assertEquals(0, s.wordStart)
+    }
+
+    @Test
+    fun aQuoteKeepsItsSentence() {
+        assertEquals("「うん」", cut("「行こう」と言った。「うん」", "うん").text)
+        assertEquals("彼は「はい。」と答えた。", cut("彼は「はい。」と答えた。次の日。", "答え").text)
+        assertEquals("彼は「はい。」", cut("彼は「はい。」と答えた。", "はい").text)
+    }
+
+    @Test
+    fun aFullStopEndsASentenceOnlyBeforeASpace() {
+        assertEquals("Then he left.", cut("He said hi. Then he left. Done", "left").text)
+        assertEquals("See v1.2 now.", cut("Old. See v1.2 now. New", "now").text)
+    }
+
+    @Test
+    fun aNewLineEndsASentenceAndIsNotKept() {
+        val s = cut("line one\nline two\nline three", "two")
+        assertEquals("line two", s.text)
+        assertEquals(5, s.wordStart)
+    }
+
+    @Test
+    fun spacesAtTheEndsGo() {
+        assertEquals("Hello there!", cut("Yes.   Hello there!  \n", "there").text)
+    }
+
+    @Test
+    fun aLongTextWithNoEndMarkIsCutAroundTheWord() {
+        val text = "あ".repeat(400)
+        val s = Sentences.around(text, 200, 202)
+        assertEquals(Sentences.MAX_SIDE + 2 + Sentences.MAX_SIDE, s.text.length)
+        assertEquals(Sentences.MAX_SIDE, s.wordStart)
+    }
+
+    @Test
+    fun aRangeOutsideTheTextIsClamped() {
+        val s = Sentences.around("abc", -3, 10)
+        assertEquals("abc", s.text)
+        assertEquals("abc", s.word)
+    }
+
+    @Test
+    fun theWordStaysAndTheSentenceIsAPieceOfTheText() = runBlocking<Unit> {
+        val chars = "あいう漢字。!?「」『』(). abcX\n".toList()
+        val texts = Arb.list(Arb.element(chars), 0..60).map { it.joinToString("") }
+        checkAll(texts, Arb.int(-2..62), Arb.int(0..10)) { text, start, length ->
+            val wordStart = start.coerceIn(0, text.length)
+            val wordEnd = (wordStart + length).coerceIn(wordStart, text.length)
+            val s = Sentences.around(text, start, wordStart + length)
+
+            assertEquals(text.substring(wordStart, wordEnd), s.word)
+            val from = wordStart - s.wordStart
+            assertTrue("the sentence is at $from in the text", text.regionMatches(from, s.text, 0, s.text.length))
+            assertEquals(wordEnd - wordStart, s.wordEnd - s.wordStart)
+            // No end mark stands before the word, outside a quote.
+            var depth = 0
+            for (i in wordStart - 1 downTo from) {
+                val c = text[i]
+                if (c in "」』))") depth++ else if (c in "「『((") depth = maxOf(0, depth - 1)
+                if (depth == 0) assertFalse("no end mark at $i in '${s.text}'", Sentences.isEnd(text, i))
+            }
+        }
+    }
+}
diff --git a/docs/intent-api.md b/docs/intent-api.md
new file mode 100644
index 0000000..0a2ff70
--- /dev/null
+++ b/docs/intent-api.md
@@ -0,0 +1,78 @@
+# The intent API of SubRead Anki
+
+Another app makes a card with one intent. SubRead Anki fills in what the app does not
+send: the definition and the audio from SubRead Dictionary, the sentence and the screenshot
+from its capture service, the sentence audio from the voice of the device. Then it puts the
+card in AnkiDroid, or shows it first when a part is missing or the user wants to see it.
+
+## The intent
+
+```kotlin
+val intent = Intent("space.subread.anki.action.ADD")
+    .setPackage("space.subread.anki")
+    .putExtra("space.subread.anki.extra.WORD", "食べる")
+    .putExtra("space.subread.anki.extra.READING", "たべる")
+    .putExtra("space.subread.anki.extra.DEFINITION", "<i>Jitendex</i><br>to eat")
+    .putExtra("space.subread.anki.extra.SENTENCE", "パンを食べた。")
+    .putExtra("space.subread.anki.extra.SOURCE", "Voice: 走れメロス")
+    .putExtra("space.subread.anki.extra.SCREENSHOT", true)
+startActivity(intent)
+```
+
+On Android 11 and later, the manifest of the sender needs the package in its queries:
+
+```xml
+<queries>
+    <package android:name="space.subread.anki" />
+</queries>
+```
+
+## The extras
+
+All extras are strings unless said otherwise. Every extra is optional, but the intent needs
+`WORD` or `TEXT`.
+
+| Extra | What |
+|---|---|
+| `space.subread.anki.extra.WORD` | The word, in its dictionary form when the sender knows it. SubRead Anki looks it up in SubRead Dictionary when `DEFINITION` is empty, and then uses the dictionary form. |
+| `space.subread.anki.extra.READING` | The reading, in kana. |
+| `space.subread.anki.extra.DEFINITION` | The definition, as simple HTML: `b`, `i`, `u`, `br`, `ul`, `li`, `a`. |
+| `space.subread.anki.extra.SENTENCE` | The sentence the word is in, as plain text. The word goes in bold when it is in the sentence as it is, or as `WORD`. |
+| `space.subread.anki.extra.TEXT` | A text with no word chosen. The card shows as a sheet, and the user taps the word in the text. |
+| `space.subread.anki.extra.IMAGE` | A content URI of an image file, as a string. See [Files](#files). |
+| `space.subread.anki.extra.AUDIO` | A content URI of the word audio, as a string. |
+| `space.subread.anki.extra.SENTENCE_AUDIO` | A content URI of the sentence audio, as a string. |
+| `space.subread.anki.extra.SOURCE` | Where the sentence is from: a book, a video, an app. Without it, the name of the sending app. |
+| `space.subread.anki.extra.URL` | A link back to the source. |
+| `space.subread.anki.extra.TAGS` | Tags for the note, separated by spaces. The tags of the settings are added to them. |
+| `space.subread.anki.extra.SCREENSHOT` | Boolean. True: when no image came and the capture service saw no selection in the last 90 seconds, take a screenshot now. The sender hides its own window for about a second before it sends the intent, so that the screenshot shows the app under it. |
+| `space.subread.anki.extra.SHOW` | Boolean. True: show the card before it goes to Anki, also when the settings say to add at once. |
+
+## Files
+
+An image or an audio file goes through a content URI, from a `FileProvider` of the sender.
+The URI string goes in the extra; the read permission goes through the clip data of the
+intent:
+
+```kotlin
+val uri = FileProvider.getUriForFile(context, "$packageName.files", file)
+intent.putExtra("space.subread.anki.extra.AUDIO", uri.toString())
+intent.clipData = ClipData.newUri(contentResolver, "audio", uri)
+intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+```
+
+With more than one file, add the other URIs as items of the same clip data. SubRead Anki
+copies each file at once, so the sender can delete it after the activity returns.
+
+## The result
+
+The activity can be started for a result. `RESULT_OK` comes with the long extra
+`space.subread.anki.extra.NOTE_ID`, the id of the note in Anki. The user can also close the
+sheet: then the result is `RESULT_CANCELED`.
+
+## The text selection menu and the share sheet
+
+Without any code, an app that has selectable text gets "Add to Anki" in its text selection
+menu (`ACTION_PROCESS_TEXT`, `text/plain`), and an app that shares text reaches SubRead Anki
+in the share sheet (`ACTION_SEND`, `text/plain`, also with an image). A short text with no
+space is the word; a longer one is a text in which the user taps the word.
diff --git a/fastlane/metadata/android/en-US/changelogs/1.txt b/fastlane/metadata/android/en-US/changelogs/1.txt
new file mode 100644
index 0000000..9dcb314
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/1.txt
@@ -0,0 +1 @@
+First release: one tap from the text selection menu, the share sheet, SubRead Dictionary or SubRead Overlay makes a card in AnkiDroid with the word, the reading, the definition, the sentence, a screenshot, the word audio and the sentence audio.
diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txt
new file mode 100644
index 0000000..16aac2f
--- /dev/null
+++ b/fastlane/metadata/android/en-US/full_description.txt
@@ -0,0 +1,7 @@
+One tap makes an Anki card on Android: the word, its reading and its definition, the sentence the word is in, a screenshot of the screen, the word audio and the sentence audio. The card goes into AnkiDroid on the device. Nothing leaves the device.
+
+It works with any app. Select a word and choose "Add to Anki" in the text selection menu, share a text, or tap "Anki" in SubRead Dictionary or SubRead Overlay.
+
+The definition, the reading and the word audio come from SubRead Dictionary, which reads Yomitan dictionaries. The sentence and the screenshot come from the capture service: an accessibility service that keeps the last text you select and a screenshot of that moment. The service is optional and off until you turn it on. The voice of the device reads the sentence.
+
+The app makes a "SubRead" note type and deck on the first card. Any other note type works: the settings map each field to a part of the card.
diff --git a/fastlane/metadata/android/en-US/short_description.txt b/fastlane/metadata/android/en-US/short_description.txt
new file mode 100644
index 0000000..26cb8c2
--- /dev/null
+++ b/fastlane/metadata/android/en-US/short_description.txt
@@ -0,0 +1 @@
+One tap makes an Anki card: word, definition, sentence, screenshot, audio.
diff --git a/fastlane/metadata/android/en-US/title.txt b/fastlane/metadata/android/en-US/title.txt
new file mode 100644
index 0000000..f443663
--- /dev/null
+++ b/fastlane/metadata/android/en-US/title.txt
@@ -0,0 +1 @@
+SubRead Anki
diff --git a/fdroid/space.subread.anki.yml b/fdroid/space.subread.anki.yml
new file mode 100644
index 0000000..84ca8ca
--- /dev/null
+++ b/fdroid/space.subread.anki.yml
@@ -0,0 +1,26 @@
+Categories:
+  - Science & Education
+License: AGPL-3.0-only
+AuthorName: equwal
+SourceCode: https://github.com/equwal/subread-anki
+IssueTracker: https://github.com/equwal/subread-anki/issues
+Changelog: https://github.com/equwal/subread-anki/releases
+Donate: https://ko-fi.com/truex
+
+AutoName: SubRead Anki
+
+RepoType: git
+Repo: https://github.com/equwal/subread-anki.git
+
+Builds:
+  - versionName: 0.1.0
+    versionCode: 1
+    commit: v0.1.0
+    subdir: app
+    gradle:
+      - yes
+
+AutoUpdateMode: Version
+UpdateCheckMode: Tags
+CurrentVersion: 0.1.0
+CurrentVersionCode: 1
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..43ba73f
--- /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 = "SubReadAnki"
+
+// Plain Kotlin: the card, the sentence cut, the furigana. Builds with a JDK alone.
+include(":core")
+include(":app")