Recently Written · git

subread-overlay

Shows the lines of an .srt over any Android media player, in time with it. Tap a word to look it up.

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

Log | Files | Refs


commit 14b481be6f3f492fe76331ac766aafecc0f5856c
equwal <truex@equwal.com>
2026-09-21 13:28:23 -0700

Show the lines of an .srt over the media player that plays

A standalone app. The panel is a window over other apps. A notification
listener holds it, because Android gives the media sessions of other
apps only to a listener; the listener reads no notification. The
follower computes the position of the player from the last report of
its media session, sleeps until the next line starts, and wakes on each
report. A tap selects the word under the finger with the word cutter of
ICU, a drag selects more words, and "Look up" sends the selection to an
app that takes a selected text.

core has the subtitle reader, the line for a position and the clock,
with property tests. The tests of the word cutter, the panel and the
follower run on a device.

 .gitignore                                         |  20 +
 LICENSE                                            | 662 +++++++++++++++++++++
 README.md                                          |  75 +++
 app/build.gradle.kts                               |  70 +++
 .../kotlin/space/subread/overlay/OverlayTest.kt    | 212 +++++++
 app/src/main/AndroidManifest.xml                   |  46 ++
 .../main/kotlin/space/subread/overlay/Follower.kt  | 110 ++++
 .../kotlin/space/subread/overlay/MainActivity.kt   | 204 +++++++
 .../kotlin/space/subread/overlay/MediaListener.kt  | 164 +++++
 .../kotlin/space/subread/overlay/OverlayView.kt    | 215 +++++++
 app/src/main/kotlin/space/subread/overlay/Store.kt |  69 +++
 app/src/main/kotlin/space/subread/overlay/Words.kt |  32 +
 app/src/main/res/drawable/icon.xml                 |   8 +
 app/src/main/res/drawable/panel.xml                |   6 +
 app/src/main/res/values/strings.xml                |  40 ++
 build.gradle.kts                                   |   5 +
 core/build.gradle.kts                              |  30 +
 .../kotlin/space/subread/overlay/core/CueIndex.kt  |  38 ++
 .../kotlin/space/subread/overlay/core/PlayClock.kt |  30 +
 .../main/kotlin/space/subread/overlay/core/Srt.kt  |  47 ++
 .../kotlin/space/subread/overlay/core/CoreTest.kt  | 146 +++++
 gradle.properties                                  |   5 +
 gradle/libs.versions.toml                          |  23 +
 gradle/wrapper/gradle-wrapper.jar                  | Bin 0 -> 45457 bytes
 gradle/wrapper/gradle-wrapper.properties           |   9 +
 gradlew                                            | 251 ++++++++
 gradlew.bat                                        |  94 +++
 settings.gradle.kts                                |  26 +
 28 files changed, 2637 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..52353e6
--- /dev/null
+++ b/README.md
@@ -0,0 +1,75 @@
+# SubRead Overlay
+
+Shows the lines of a subtitle file (`.srt`) over the app that plays your
+audiobook or video. The line follows the position of the player. Tap a word to
+select it, and send it to a dictionary.
+
+It works with each Android player that publishes a media session: Voice, VLC,
+mpv-android, YouTube, Smart AudioBook Player, podcast apps. No player needs a
+change, and the app has no network permission.
+
+No `.srt` for your audiobook? [SubRead](https://subread.space) makes one from
+the audiobook and its ebook, in the browser or on
+[Android](https://github.com/equwal/subread-android).
+
+## How to use it
+
+1. Allow "Show over other apps".
+2. Allow notification access. Android gives the position of other apps only to
+   an app with this access. The app uses it for the media position, the speed,
+   and play or pause. It does not read, keep or send a notification: the
+   listener has no `onNotificationPosted`.
+3. Choose the `.srt` file.
+4. Choose the dictionary for "Look up", or let Android ask each time. Each app
+   that has an entry in the text selection menu is in the list (Takoboto,
+   Aedict, AnkiDroid, a translator).
+5. Press "Show the subtitles", then start the player.
+
+On the panel:
+
+- `≡` moves the panel.
+- A tap selects the word under the finger. A drag selects more words.
+  "Look up" sends the selection to the dictionary. "Copy" copies it.
+- `⋯` opens the timing row. `−0.5 s` and `+0.5 s` shift the subtitles.
+  `◀ line` and `line ▶` make the line before, or the next line, the line of
+  now. Use them when the media has an intro that the subtitle file does not
+  have.
+- `✕` closes the panel.
+
+The line stays on the panel until the next line starts, also in a silence, so
+that there is time to look a word up.
+
+## How the timing works
+
+A media session reports a position, the time of that report, and the speed.
+`PlayClock` computes the position of now from these three. `Follower` sleeps
+until the next line starts and wakes on each report of the player (pause,
+seek, speed). It does not poll.
+
+A player that reports no position: Android counts from zero when that player
+starts to play, and the panel holds its line in a pause. Set the timing with
+`◀ line` and `line ▶`.
+
+The app does not use an accessibility service, and will not. Players that
+hide their position (Netflix, some DRM players) are not supported.
+
+A book in many audio files: the player reports the position in the current
+file, and the subtitle file has one clock for the whole book. Shift the
+subtitles with the timing row at the start of each file. One `.m4b` for one
+book has no such problem.
+
+## Build
+
+```
+./gradlew :core:test :app:assembleDebug
+./gradlew :app:connectedDebugAndroidTest   # word selection and the follower, on a device
+```
+
+`:core` is plain Kotlin: the subtitle reader, the line for a position, the
+clock. It has property tests. `:app` has the panel and the listener.
+
+`-PplayStore=true` leaves the Ko-fi link out of the build for Google Play.
+
+## Licence
+
+AGPL-3.0. See `LICENSE`.
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
new file mode 100644
index 0000000..eb66273
--- /dev/null
+++ b/app/build.gradle.kts
@@ -0,0 +1,70 @@
+plugins {
+    alias(libs.plugins.android.application)
+}
+
+// Release signing comes from the environment, so the key never lives in the repository.
+val keystorePath = providers.environmentVariable("SUBREAD_KEYSTORE_FILE").orNull
+val keystorePassword = providers.environmentVariable("SUBREAD_KEYSTORE_PASSWORD").orNull
+val signingReady = !keystorePath.isNullOrBlank() && !keystorePassword.isNullOrBlank() &&
+    file(keystorePath).isFile
+
+android {
+    namespace = "space.subread.overlay"
+    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.overlay"
+        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), the same
+        // as in the SubRead app.
+        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/androidTest/kotlin/space/subread/overlay/OverlayTest.kt b/app/src/androidTest/kotlin/space/subread/overlay/OverlayTest.kt
new file mode 100644
index 0000000..f332b29
--- /dev/null
+++ b/app/src/androidTest/kotlin/space/subread/overlay/OverlayTest.kt
@@ -0,0 +1,212 @@
+package space.subread.overlay
+
+import android.media.session.MediaController
+import android.media.session.MediaSession
+import android.media.session.PlaybackState
+import android.os.Handler
+import android.os.Looper
+import android.os.SystemClock
+import android.view.ViewGroup
+import androidx.test.core.app.ActivityScenario
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import space.subread.overlay.core.Cue
+import space.subread.overlay.core.CueIndex
+import java.util.concurrent.CopyOnWriteArrayList
+
+/** The word cutter of the device. It is ICU of Android, so the test runs on the device. */
+@RunWith(AndroidJUnit4::class)
+class WordsTest {
+
+    private fun word(text: String, offset: Int) = Words.at(text, offset)?.let { text.substring(it.first, it.last + 1) }
+
+    @Test
+    fun aWordOfALanguageWithSpaces() {
+        val text = "Он вышел из дома, and never came back."
+        assertEquals("вышел", word(text, text.indexOf("шел")))
+        assertEquals("never", word(text, text.indexOf("never")))
+        assertNull("a space", word(text, 2))
+        assertNull("a comma", word(text, text.indexOf(',')))
+        assertNull(word(text, text.length))
+        assertNull(word("", 0))
+    }
+
+    @Test
+    fun aWordOfJapaneseThatHasNoSpaces() {
+        val text = "女のいない男たちは、東京で暮らしている。"
+        // The dictionary of ICU decides the cut. The test asks for what each good cut has:
+        // a word is shorter than the sentence, stops at the comma, and has the character under the finger.
+        for (at in listOf(0, text.indexOf("男"), text.indexOf("東京"), text.indexOf("暮"))) {
+            val range = Words.at(text, at)!!
+            assertTrue("$range has $at", at in range)
+            assertTrue("$range is a word, not the sentence", range.last - range.first < 6)
+            assertTrue("no comma in a word", '、' !in text.substring(range.first, range.last + 1))
+        }
+        assertEquals("東京", word(text, text.indexOf("東京")))
+        assertNull(word(text, text.indexOf('、')))
+    }
+
+    @Test
+    fun aDragSelectsFromTheFirstWordToTheWordUnderTheFinger() {
+        val text = "one two three four"
+        val anchor = Words.at(text, text.indexOf("two"))!!
+        assertEquals("two three", Words.between(text, anchor, text.indexOf("three")).let { text.substring(it.first, it.last + 1) })
+        assertEquals("one two", Words.between(text, anchor, 0).let { text.substring(it.first, it.last + 1) })
+        assertEquals("a drag over a space keeps the selection", anchor, Words.between(text, anchor, 3))
+    }
+}
+
+/** The panel, in the window of an activity: the test needs no permission that way. */
+@RunWith(AndroidJUnit4::class)
+class OverlayViewTest {
+
+    private val lookedUp = CopyOnWriteArrayList<String>()
+    private val events = object : OverlayView.Events {
+        override fun onDrag(dx: Float, dy: Float) = Unit
+        override fun onDragEnd() = Unit
+        override fun onClose() = Unit
+        override fun onLookUp(word: String) { lookedUp += word }
+        override fun onShiftLines(steps: Int) = Unit
+        override fun onNudge(ms: Long) = Unit
+    }
+
+    @Test
+    fun aTapSelectsTheWordUnderTheFingerAndLookUpSendsIt() {
+        ActivityScenario.launch(MainActivity::class.java).use { scenario ->
+            lateinit var panel: OverlayView
+            scenario.onActivity {
+                panel = OverlayView(it, events)
+                panel.setTextSize(30f)
+                it.addContentView(panel, ViewGroup.LayoutParams(-1, -2))
+                panel.showLine("reading along is easy")
+            }
+            InstrumentationRegistry.getInstrumentation().waitForIdleSync()
+            scenario.onActivity {
+                val layout = panel.text.layout
+                val start = panel.line.indexOf("along")
+                // The middle of the third letter of "along".
+                val x = panel.text.totalPaddingLeft + (layout.getPrimaryHorizontal(start + 2) + layout.getPrimaryHorizontal(start + 3)) / 2
+                val y = panel.text.totalPaddingTop + layout.getLineBaseline(0) - 5f
+                panel.selectAt(x, y)
+                assertEquals(start..start + 4, panel.selection)
+
+                // A drag to the last word selects the three words.
+                val end = panel.text.totalPaddingLeft + layout.getPrimaryHorizontal(panel.line.length - 1) - 2f
+                panel.selectAt(end, y, extend = true)
+                assertEquals(start..panel.line.lastIndex, panel.selection)
+
+                val found = arrayListOf<android.view.View>()
+                panel.findViewsWithText(found, "Look up", android.view.View.FIND_VIEWS_WITH_TEXT)
+                found.single().performClick()
+                assertEquals(listOf("along is easy"), lookedUp)
+
+                // The next line has no selection from the line before.
+                panel.showLine("the next line")
+                assertNull(panel.selection)
+            }
+        }
+    }
+}
+
+/** A media session of the test plays the part of Voice, VLC or YouTube. */
+@RunWith(AndroidJUnit4::class)
+class FollowerTest {
+
+    private val context = InstrumentationRegistry.getInstrumentation().targetContext
+    private val main = Handler(Looper.getMainLooper())
+    private val lines = CopyOnWriteArrayList<String?>()
+    private val index = CueIndex(listOf(Cue(1_000, 2_000, "one"), Cue(60_000, 61_000, "two"), Cue(60_400, 61_000, "three")))
+
+    private fun state(state: Int, position: Long, speed: Float = 1f) = PlaybackState.Builder()
+        .setState(state, position, speed, SystemClock.elapsedRealtime()).build()
+
+    private fun onMain(block: () -> Unit) = InstrumentationRegistry.getInstrumentation().runOnMainSync(block)
+
+    private fun waitFor(line: String?) {
+        val until = SystemClock.elapsedRealtime() + 5_000
+        while (lines.lastOrNull() != line && SystemClock.elapsedRealtime() < until) Thread.sleep(20)
+        assertEquals(lines.toString(), line, lines.lastOrNull())
+    }
+
+    @Test
+    fun theLineFollowsThePlayerThroughPauseSeekSpeedAndOffset() {
+        val session = MediaSession(context, "test player")
+        lateinit var follower: Follower
+        try {
+            session.setPlaybackState(state(PlaybackState.STATE_PAUSED, 1_500))
+            session.isActive = true
+            onMain {
+                follower = Follower(main) { cue, _ -> lines += cue?.text }
+                follower.index = index
+                follower.follow(listOf(MediaController(context, session.sessionToken)))
+            }
+            waitFor("one")
+
+            // A seek. The player is paused: the line changes at once and then stays.
+            session.setPlaybackState(state(PlaybackState.STATE_PAUSED, 500))
+            waitFor(null)
+
+            // Play at double speed from 59.6 s: "two" is 0.2 s away, "three" 0.2 s after it.
+            val started = SystemClock.elapsedRealtime()
+            session.setPlaybackState(state(PlaybackState.STATE_PLAYING, 59_600, speed = 2f))
+            waitFor("one")
+            waitFor("two")
+            waitFor("three")
+            val took = SystemClock.elapsedRealtime() - started
+            assertTrue("the follower waited $took ms; at double speed 0.8 s of media is 0.4 s", took in 350..1_500)
+
+            // The subtitles are 60 s late for this media: the user shifts them.
+            session.setPlaybackState(state(PlaybackState.STATE_PAUSED, 100))
+            waitFor(null)
+            onMain { follower.offsetMs = 60_000 }
+            waitFor("two")
+
+            // "line ▶" makes the next line the line of now.
+            onMain { follower.shiftLines(1) }
+            waitFor("three")
+            onMain { assertEquals(60_400L - 100L, follower.offsetMs) }
+        } finally {
+            onMain { follower.stop() }
+            session.release()
+        }
+    }
+
+    @Test
+    fun aPlayerWithoutAPositionKeepsItsLineWhenItPauses() {
+        val session = MediaSession(context, "player without position")
+        lateinit var follower: Follower
+        try {
+            session.setPlaybackState(state(PlaybackState.STATE_PLAYING, PlaybackState.PLAYBACK_POSITION_UNKNOWN))
+            session.isActive = true
+            onMain {
+                follower = Follower(main) { cue, _ -> lines += cue?.text }
+                follower.index = CueIndex(listOf(Cue(0, 300, "first"), Cue(400, 900, "second")))
+                follower.follow(listOf(MediaController(context, session.sessionToken)))
+            }
+            // Android counts from zero for a player that plays and gives no position.
+            waitFor("second")
+            // In a pause there is no position at all. The first version went back to "before the first line".
+            session.setPlaybackState(state(PlaybackState.STATE_PAUSED, PlaybackState.PLAYBACK_POSITION_UNKNOWN))
+            Thread.sleep(500)
+            assertEquals(lines.toString(), "second", lines.last())
+        } finally {
+            onMain { follower.stop() }
+            session.release()
+        }
+    }
+
+    @Test
+    fun noPlayerIsSaidSo() {
+        val players = CopyOnWriteArrayList<Boolean>()
+        onMain {
+            val follower = Follower(main) { _, hasPlayer -> players += hasPlayer }
+            follower.follow(emptyList())
+        }
+        assertEquals(false, players.last())
+    }
+}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..79df7ca
--- /dev/null
+++ b/app/src/main/AndroidManifest.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+    <!-- The subtitle line is drawn over the media player. No network permission: nothing leaves the device. -->
+    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
+
+    <!-- The apps that can take a word: dictionaries, translators, flash card apps. -->
+    <queries>
+        <intent>
+            <action android:name="android.intent.action.PROCESS_TEXT" />
+            <data android:mimeType="text/plain" />
+        </intent>
+    </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">
+
+        <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>
+
+        <!--
+            Android gives the play position of other apps only to a notification listener.
+            This service reads no notification. The system keeps it running, so the overlay
+            needs no foreground service and no notification of its own.
+        -->
+        <service
+            android:name=".MediaListener"
+            android:exported="true"
+            android:label="@string/listener_label"
+            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
+            <intent-filter>
+                <action android:name="android.service.notification.NotificationListenerService" />
+            </intent-filter>
+        </service>
+    </application>
+</manifest>
diff --git a/app/src/main/kotlin/space/subread/overlay/Follower.kt b/app/src/main/kotlin/space/subread/overlay/Follower.kt
new file mode 100644
index 0000000..0f07385
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/overlay/Follower.kt
@@ -0,0 +1,110 @@
+package space.subread.overlay
+
+import android.media.session.MediaController
+import android.media.session.PlaybackState
+import android.os.Handler
+import android.os.SystemClock
+import space.subread.overlay.core.Cue
+import space.subread.overlay.core.CueIndex
+import space.subread.overlay.core.PlayClock
+
+/**
+ * Follows the media player that plays now, and says which subtitle line is on.
+ *
+ * Each Android media player publishes a media session: Voice, VLC, mpv, YouTube, a podcast app.
+ * The session has the position, the time of that position and the speed. The follower computes
+ * the position between two reports, and sleeps until the next line starts. It does not poll.
+ *
+ * A player that publishes no position: Android makes a position for it that starts at zero when
+ * the player starts to play, and gives none while the player is paused. The follower then holds
+ * the last position, so the line stays. The user sets the timing with the line buttons.
+ */
+class Follower(
+    private val handler: Handler,
+    private val now: () -> Long = SystemClock::elapsedRealtime,
+    /** The line that is on, and true when there is a player to follow. */
+    private val onLine: (Cue?, Boolean) -> Unit,
+) {
+    var index: CueIndex = CueIndex(emptyList())
+        set(value) {
+            field = value
+            update()
+        }
+
+    /** Added to the position of the player, in milliseconds: a file with an intro, a player that is late. */
+    var offsetMs: Long = 0
+        set(value) {
+            field = value
+            update()
+        }
+
+    private var controller: MediaController? = null
+    private var last: PlayClock? = null
+    private val wake = Runnable { update() }
+
+    private val callback = object : MediaController.Callback() {
+        override fun onPlaybackStateChanged(state: PlaybackState?) = update()
+        override fun onSessionDestroyed() = follow(emptyList())
+    }
+
+    /**
+     * The sessions that are active, in the order of the system: the one that plays is first.
+     * The follower keeps its player while that player is in the list and no other one plays.
+     */
+    fun follow(controllers: List<MediaController>) {
+        val playing = controllers.firstOrNull { it.playbackState?.state == PlaybackState.STATE_PLAYING }
+        val kept = controllers.firstOrNull { it.sessionToken == controller?.sessionToken }
+        val next = playing ?: kept ?: controllers.firstOrNull()
+        if (next?.sessionToken != controller?.sessionToken) {
+            controller?.unregisterCallback(callback)
+            controller = next
+            last = null
+            next?.registerCallback(callback, handler)
+        }
+        update()
+    }
+
+    fun stop() {
+        handler.removeCallbacks(wake)
+        controller?.unregisterCallback(callback)
+        controller = null
+    }
+
+    /** Makes the line [steps] lines from the line that is on the current line, by a change of [offsetMs]. */
+    fun shiftLines(steps: Int) {
+        val clock = clock() ?: return
+        if (index.size == 0) return
+        val position = clock.positionAt(now())
+        val target = (index.indexAt(position + offsetMs) + steps).coerceIn(0, index.size - 1)
+        offsetMs = index.cues[target].startMs - position
+    }
+
+    private fun clock(): PlayClock? {
+        val state = controller?.playbackState ?: return null
+        val playing = state.state == PlaybackState.STATE_PLAYING
+        val clock = if (state.position >= 0) {
+            // Some players leave the time of the report at zero. Then the report is from now.
+            val reportedAt = state.lastPositionUpdateTime.takeIf { it > 0 } ?: now()
+            val speed = state.playbackSpeed.takeIf { it > 0f } ?: 1f
+            PlayClock(state.position, reportedAt, speed, playing)
+        } else {
+            // No position in this report: hold the position of the report before.
+            PlayClock(last?.positionAt(now()) ?: 0, now(), 1f, playing)
+        }
+        return clock.also { last = it }
+    }
+
+    private fun update() {
+        handler.removeCallbacks(wake)
+        val clock = clock()
+        if (clock == null) {
+            onLine(null, false)
+            return
+        }
+        val position = clock.positionAt(now()) + offsetMs
+        val at = index.indexAt(position)
+        onLine(index.cues.getOrNull(at), true)
+        val next = index.nextChangeAfter(position) ?: return
+        clock.waitUntil(next - offsetMs, now())?.let { handler.postDelayed(wake, it) }
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/overlay/MainActivity.kt b/app/src/main/kotlin/space/subread/overlay/MainActivity.kt
new file mode 100644
index 0000000..4141711
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/overlay/MainActivity.kt
@@ -0,0 +1,204 @@
+package space.subread.overlay
+
+import android.annotation.SuppressLint
+import android.app.Activity
+import android.app.AlertDialog
+import android.content.ComponentName
+import android.content.Intent
+import android.graphics.Color
+import android.graphics.Typeface
+import android.net.Uri
+import android.os.Bundle
+import android.provider.OpenableColumns
+import android.provider.Settings
+import android.view.View
+import android.widget.Button
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
+import android.widget.Toast
+import androidx.core.net.toUri
+import space.subread.overlay.core.Srt
+
+/**
+ * The one screen of the app: the two permissions, the subtitle file, the dictionary, the text
+ * size, and the button for the panel. Each part is on the screen from the start, so that the
+ * user sees what the app does before a button is pressed.
+ */
+class MainActivity : Activity() {
+
+    private lateinit var store: Store
+    private lateinit var content: LinearLayout
+
+    override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+        store = Store(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 here, so the state is read again. */
+    override fun onResume() {
+        super.onResume()
+        draw()
+    }
+
+    private fun draw() {
+        content.removeAllViews()
+        val overlay = Settings.canDrawOverlays(this)
+        val listener = MediaListener.isAllowed(this)
+
+        title(getString(R.string.app_name))
+        note(getString(R.string.about))
+        note(getString(R.string.privacy))
+
+        step(R.string.step_overlay, getString(R.string.step_overlay_why), if (overlay) null else getString(R.string.allow), overlay) {
+            startActivity(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, "package:$packageName".toUri()))
+        }
+        step(R.string.step_listener, getString(R.string.step_listener_why), if (listener) null else getString(R.string.allow), listener) {
+            startActivity(Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS))
+        }
+        step(R.string.step_file, store.subtitlesName ?: getString(R.string.step_file_none), getString(R.string.choose)) {
+            startActivityForResult(
+                Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*"),
+                PICK_SUBTITLES,
+            )
+        }
+        step(R.string.step_dictionary, dictionaryName(), getString(R.string.choose)) { chooseDictionary() }
+        step(R.string.step_size, "${store.textSizeSp.toInt()} sp", null) {}
+        row(button("−") { size(-2f) }, button("+") { size(2f) })
+
+        val shown = store.shown && MediaListener.instance != null
+        content.addView(button(getString(if (shown) R.string.hide else R.string.show)) { togglePanel() }.apply {
+            setTypeface(typeface, Typeface.BOLD)
+        }, wide(top = 24))
+
+        note(getString(R.string.make_subtitles), top = 32)
+        content.addView(button(getString(R.string.make_subtitles_action)) { open(SUBREAD) }, wide())
+        if (BuildConfig.DONATE_LINK) content.addView(button(getString(R.string.donate)) { open(KOFI) }, wide())
+    }
+
+    private fun togglePanel() {
+        val service = MediaListener.instance
+        when {
+            !Settings.canDrawOverlays(this) || !MediaListener.isAllowed(this) -> toast(R.string.need_both)
+            service == null -> toast(R.string.listener_starting)
+            store.shown -> service.hidePanel()
+            else -> service.showPanel()
+        }
+        draw()
+    }
+
+    private fun size(change: Float) {
+        store.textSizeSp += change
+        MediaListener.instance?.reload()
+        draw()
+    }
+
+    private fun dictionaryName(): String {
+        val chosen = store.dictionary ?: return getString(R.string.dictionary_ask)
+        return dictionaries().firstOrNull { it.second == chosen }?.first ?: getString(R.string.dictionary_ask)
+    }
+
+    /** The apps that take a selected text, with the name that each one gives the entry. */
+    private fun dictionaries(): List<Pair<String, ComponentName>> =
+        packageManager.queryIntentActivities(Lookup.probe(), 0).map {
+            val app = it.activityInfo.applicationInfo.loadLabel(packageManager)
+            val entry = it.loadLabel(packageManager)
+            val name = if (entry.toString() == app.toString()) "$app" else "$app: $entry"
+            name to ComponentName(it.activityInfo.packageName, it.activityInfo.name)
+        }.sortedBy { it.first }
+
+    private fun chooseDictionary() {
+        val found = dictionaries()
+        if (found.isEmpty()) {
+            AlertDialog.Builder(this).setMessage(R.string.dictionary_none).setPositiveButton(android.R.string.ok, null).show()
+            return
+        }
+        val names = listOf(getString(R.string.dictionary_ask)) + found.map { it.first }
+        AlertDialog.Builder(this).setItems(names.toTypedArray()) { _, which ->
+            store.dictionary = found.getOrNull(which - 1)?.second
+            draw()
+        }.show()
+    }
+
+    @Deprecated("The platform Activity has no other result API, and this app has no AndroidX activity.")
+    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+        val uri = data?.data
+        if (requestCode != PICK_SUBTITLES || resultCode != RESULT_OK || uri == null) return
+        // The listener reads the file later, also after a restart of the device.
+        runCatching { contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) }
+        val lines = runCatching {
+            contentResolver.openInputStream(uri)!!.use { Srt.parse(it.readBytes().decodeToString()) }.size
+        }.getOrDefault(0)
+        store.subtitles = uri
+        store.subtitlesName = resources.getQuantityString(R.plurals.step_file_cues, lines, displayName(uri), lines)
+        MediaListener.instance?.reload()
+        draw()
+    }
+
+    private fun displayName(uri: Uri): String =
+        contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use {
+            if (it.moveToFirst()) it.getString(0) else null
+        } ?: uri.lastPathSegment.orEmpty()
+
+    private fun open(link: String) {
+        runCatching { startActivity(Intent(Intent.ACTION_VIEW, link.toUri())) }
+    }
+
+    private fun toast(message: Int) = Toast.makeText(this, message, Toast.LENGTH_LONG).show()
+
+    // The screen is built in code: six 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) = content.addView(TextView(this).apply {
+        text = value
+        textSize = 15f
+        setTextColor(Color.BLACK)
+    }, wide(top))
+
+    @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.allowed)}" else ""
+            textSize = 18f
+            setTypeface(typeface, Typeface.BOLD)
+            setTextColor(Color.BLACK)
+        }, wide(top = 12))
+        note(detail, top = 4)
+        if (action != null) content.addView(button(action, onAction), LinearLayout.LayoutParams(-2, -2))
+    }
+
+    private fun row(vararg views: View) = content.addView(LinearLayout(this).apply { views.forEach { addView(it) } })
+
+    private fun button(label: String, onClick: () -> Unit) = Button(this).apply {
+        text = label
+        isAllCaps = false
+        setOnClickListener { onClick() }
+    }
+
+    private fun wide(top: Int = 8) = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(top) }
+
+    private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
+
+    private companion object {
+        const val PICK_SUBTITLES = 1
+        const val SUBREAD = "https://subread.space/?utm_source=overlay_app"
+        const val KOFI = "https://ko-fi.com/truex"
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/overlay/MediaListener.kt b/app/src/main/kotlin/space/subread/overlay/MediaListener.kt
new file mode 100644
index 0000000..3ed2a1a
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/overlay/MediaListener.kt
@@ -0,0 +1,164 @@
+package space.subread.overlay
+
+import android.content.ComponentName
+import android.content.Context
+import android.graphics.PixelFormat
+import android.media.session.MediaSessionManager
+import android.os.Handler
+import android.os.Looper
+import android.provider.Settings
+import android.service.notification.NotificationListenerService
+import android.view.Gravity
+import android.view.WindowManager
+import android.widget.Toast
+import space.subread.overlay.core.CueIndex
+import space.subread.overlay.core.Srt
+import kotlin.concurrent.thread
+
+/**
+ * Holds the panel, and follows the media sessions of the device.
+ *
+ * Android gives the media sessions of other apps only to a notification listener. This service
+ * reads no notification: it has no `onNotificationPosted`. The system keeps a listener running,
+ * so the panel needs no foreground service and no notification of its own.
+ */
+class MediaListener : NotificationListenerService(), OverlayView.Events {
+
+    private val handler = Handler(Looper.getMainLooper())
+    private lateinit var store: Store
+    private lateinit var follower: Follower
+    private var panel: OverlayView? = null
+    private val params = WindowManager.LayoutParams(
+        WindowManager.LayoutParams.MATCH_PARENT,
+        WindowManager.LayoutParams.WRAP_CONTENT,
+        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
+        // The player below keeps the keys and each touch that is not on the panel.
+        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
+        PixelFormat.TRANSLUCENT,
+    ).apply { gravity = Gravity.TOP or Gravity.START }
+
+    private val sessions by lazy { getSystemService(MediaSessionManager::class.java) }
+    private val me by lazy { ComponentName(this, MediaListener::class.java) }
+    private val onSessions = MediaSessionManager.OnActiveSessionsChangedListener {
+        // A hidden panel follows nothing: no work while the user does not read along.
+        if (panel != null) follower.follow(it.orEmpty())
+    }
+
+    override fun onListenerConnected() {
+        store = Store(this)
+        follower = Follower(handler) { cue, hasPlayer -> show(cue?.text, hasPlayer) }
+        sessions.addOnActiveSessionsChangedListener(onSessions, me, handler)
+        instance = this
+        if (store.shown) showPanel()
+    }
+
+    override fun onListenerDisconnected() {
+        instance = null
+        sessions.removeOnActiveSessionsChangedListener(onSessions)
+        follower.stop()
+        removePanel()
+    }
+
+    /** Puts the panel on the screen. False when the user did not allow the panel yet. */
+    fun showPanel(): Boolean {
+        if (!Settings.canDrawOverlays(this)) return false
+        store.shown = true
+        if (panel == null) {
+            params.x = store.x
+            params.y = store.y
+            panel = OverlayView(this, this).also { getSystemService(WindowManager::class.java).addView(it, params) }
+        }
+        reload()
+        return true
+    }
+
+    fun hidePanel() {
+        store.shown = false
+        follower.stop()
+        removePanel()
+    }
+
+    /** Reads the settings and the subtitle file again. */
+    fun reload() {
+        val view = panel ?: return
+        view.setTextSize(store.textSizeSp)
+        view.showOffset(store.offsetMs)
+        follower.offsetMs = store.offsetMs
+        val file = store.subtitles
+        if (file == null) {
+            follower.index = CueIndex(emptyList())
+            return
+        }
+        thread(name = "subtitles") {
+            val cues = runCatching {
+                contentResolver.openInputStream(file)!!.use { Srt.parse(it.readBytes().decodeToString()) }
+            }.getOrDefault(emptyList())
+            handler.post {
+                follower.index = CueIndex(cues)
+                follower.follow(sessions.getActiveSessions(me))
+            }
+        }
+    }
+
+    private fun removePanel() {
+        panel?.let { getSystemService(WindowManager::class.java).removeView(it) }
+        panel = null
+    }
+
+    private fun show(line: String?, hasPlayer: Boolean) {
+        val view = panel ?: return
+        when {
+            store.subtitles == null -> view.showStatus(getString(R.string.status_no_file))
+            follower.index.size == 0 -> view.showStatus(getString(R.string.status_empty_file))
+            !hasPlayer -> view.showStatus(getString(R.string.status_no_player))
+            line == null -> view.showStatus(getString(R.string.status_before_first_line))
+            else -> view.showLine(line)
+        }
+    }
+
+    override fun onDrag(dx: Float, dy: Float) {
+        params.x += dx.toInt()
+        params.y += dy.toInt()
+        panel?.let { getSystemService(WindowManager::class.java).updateViewLayout(it, params) }
+    }
+
+    override fun onDragEnd() {
+        store.x = params.x
+        store.y = params.y
+    }
+
+    override fun onClose() = hidePanel()
+
+    override fun onLookUp(word: String) {
+        runCatching { startActivity(Lookup.intent(word, store.dictionary)) }.onFailure {
+            Toast.makeText(this, R.string.no_dictionary, Toast.LENGTH_LONG).show()
+        }
+    }
+
+    override fun onShiftLines(steps: Int) {
+        follower.shiftLines(steps)
+        keepOffset()
+    }
+
+    override fun onNudge(ms: Long) {
+        follower.offsetMs += ms
+        keepOffset()
+    }
+
+    private fun keepOffset() {
+        store.offsetMs = follower.offsetMs
+        panel?.showOffset(follower.offsetMs)
+    }
+
+    companion object {
+        /** The listener that the system runs now; null when the user did not allow it. */
+        @Volatile
+        var instance: MediaListener? = null
+            private set
+
+        fun isAllowed(context: Context): Boolean =
+            Settings.Secure.getString(context.contentResolver, "enabled_notification_listeners")
+                ?.split(':')?.mapNotNull(ComponentName::unflattenFromString)
+                ?.any { it.packageName == context.packageName } == true
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/overlay/OverlayView.kt b/app/src/main/kotlin/space/subread/overlay/OverlayView.kt
new file mode 100644
index 0000000..a072163
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/overlay/OverlayView.kt
@@ -0,0 +1,215 @@
+package space.subread.overlay
+
+import android.annotation.SuppressLint
+import android.content.ClipData
+import android.content.ClipboardManager
+import android.content.Context
+import android.graphics.Color
+import android.graphics.Typeface
+import android.text.SpannableString
+import android.text.Spanned
+import android.text.style.BackgroundColorSpan
+import android.text.style.ForegroundColorSpan
+import android.util.TypedValue
+import android.view.Gravity
+import android.view.MotionEvent
+import android.view.View
+import android.widget.Button
+import android.widget.LinearLayout
+import android.widget.TextView
+import androidx.core.view.isVisible
+
+/**
+ * The panel over the media player: the subtitle line, and a few buttons.
+ *
+ * A tap on the line selects the word under the finger. A drag makes the selection longer, word
+ * by word. The selection goes to a dictionary with "Look up". The system text selection is not
+ * used: it needs a window with the input focus, and then the player below gets no keys.
+ *
+ * Black on white and nothing that moves, so that the panel is usable on an e-ink screen.
+ */
+@SuppressLint("ViewConstructor", "SetTextI18n")
+class OverlayView(context: Context, private val events: Events) : LinearLayout(context) {
+
+    interface Events {
+        fun onDrag(dx: Float, dy: Float)
+        fun onDragEnd()
+        fun onClose()
+        fun onLookUp(word: String)
+        fun onShiftLines(steps: Int)
+        fun onNudge(ms: Long)
+    }
+
+    /** The line on the panel, without the selection marks. */
+    var line: String = ""
+        private set
+
+    /** The part of [line] that is selected. */
+    var selection: IntRange? = null
+        private set
+
+    val text = TextView(context)
+    private val lookUpRow = LinearLayout(context)
+    private val syncRow = LinearLayout(context)
+    private val offsetLabel = TextView(context)
+    private var anchor: IntRange? = null
+
+    init {
+        orientation = VERTICAL
+        setBackgroundResource(R.drawable.panel)
+        val pad = dp(6)
+        setPadding(pad, pad, pad, pad)
+
+        val top = LinearLayout(context).apply { gravity = Gravity.CENTER_VERTICAL }
+        top.addView(button("≡", "Move the subtitles") {}.also(::dragWith), wrap())
+        text.setTextColor(Color.BLACK)
+        text.typeface = Typeface.DEFAULT
+        text.setPadding(dp(8), dp(4), dp(8), dp(4))
+        text.setLineSpacing(0f, 1.15f)
+        selectWith(text)
+        top.addView(text, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f))
+        top.addView(button("⋯", "Timing") { toggle(syncRow) }, wrap())
+        top.addView(button("✕", "Close the subtitles") { events.onClose() }, wrap())
+        addView(top, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
+
+        lookUpRow.gravity = Gravity.END
+        lookUpRow.addView(button("Copy", null) { copy() }, wrap())
+        lookUpRow.addView(button("Look up", null) { lookUp() }, wrap())
+        lookUpRow.visibility = View.GONE
+        addView(lookUpRow, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
+
+        syncRow.gravity = Gravity.CENTER
+        syncRow.addView(button("◀ line", "The line before is the line now") { events.onShiftLines(-1) }, wrap())
+        syncRow.addView(button("−0.5 s", "Subtitles later") { events.onNudge(-500) }, wrap())
+        offsetLabel.setTextColor(Color.BLACK)
+        offsetLabel.setPadding(dp(8), 0, dp(8), 0)
+        syncRow.addView(offsetLabel, wrap())
+        syncRow.addView(button("+0.5 s", "Subtitles sooner") { events.onNudge(500) }, wrap())
+        syncRow.addView(button("line ▶", "The next line is the line now") { events.onShiftLines(1) }, wrap())
+        syncRow.visibility = View.GONE
+        addView(syncRow, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
+    }
+
+    fun setTextSize(sp: Float) = text.setTextSize(TypedValue.COMPLEX_UNIT_SP, sp)
+
+    fun showOffset(ms: Long) {
+        offsetLabel.text = "%+.1f s".format(ms / 1000.0)
+    }
+
+    /** Shows a subtitle line. The selection goes away when the line changes. */
+    fun showLine(value: String) {
+        if (value == line) return
+        line = value
+        text.setTypeface(Typeface.DEFAULT, Typeface.NORMAL)
+        select(null)
+    }
+
+    /** Shows a word of the app to the user, where the line would be: no player, no file. */
+    fun showStatus(value: String) {
+        line = ""
+        selection = null
+        lookUpRow.visibility = View.GONE
+        text.setTypeface(Typeface.DEFAULT, Typeface.ITALIC)
+        text.text = value
+    }
+
+    /** Selects the word at the point [x], [y] of the text view. For a tap, and for tests. */
+    fun selectAt(x: Float, y: Float, extend: Boolean = false) {
+        val offset = offsetAt(x, y) ?: return select(if (extend) selection else null)
+        val from = anchor
+        if (extend && from != null) {
+            select(Words.between(line, from, offset))
+        } else {
+            anchor = Words.at(line, offset)
+            select(anchor)
+        }
+    }
+
+    private fun select(range: IntRange?) {
+        selection = range
+        if (range == null) anchor = null
+        val marked = SpannableString(line)
+        if (range != null) {
+            marked.setSpan(BackgroundColorSpan(Color.BLACK), range.first, range.last + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
+            marked.setSpan(ForegroundColorSpan(Color.WHITE), range.first, range.last + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
+        }
+        text.text = marked
+        lookUpRow.visibility = if (range == null) View.GONE else View.VISIBLE
+    }
+
+    /** The index of the character under the point; null when the point is not on a character. */
+    private fun offsetAt(x: Float, y: Float): Int? {
+        val layout = text.layout ?: return null
+        if (line.isEmpty()) return null
+        val inX = x - text.totalPaddingLeft
+        val inY = y - text.totalPaddingTop
+        if (inY < 0 || inY > layout.height) return null
+        val row = layout.getLineForVertical(inY.toInt())
+        if (inX < layout.getLineLeft(row) || inX > layout.getLineRight(row)) return null
+        // The offset of a point is a place between two characters. The character under the
+        // finger is the one before that place when the finger is on its right half.
+        val between = layout.getOffsetForHorizontal(row, inX)
+        val under = if (between > layout.getLineStart(row) && layout.getPrimaryHorizontal(between) > inX) between - 1 else between
+        return under.coerceIn(0, line.length - 1)
+    }
+
+    private fun selected(): String? = selection?.let { line.substring(it.first, it.last + 1) }
+
+    private fun lookUp() {
+        events.onLookUp(selected() ?: return)
+    }
+
+    private fun copy() {
+        val word = selected() ?: return
+        context.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("subtitle", word))
+    }
+
+    @SuppressLint("ClickableViewAccessibility") // The buttons of the panel do the same for a screen reader.
+    private fun selectWith(view: TextView) {
+        view.setOnTouchListener { _, event ->
+            when (event.actionMasked) {
+                MotionEvent.ACTION_DOWN -> selectAt(event.x, event.y)
+                MotionEvent.ACTION_MOVE -> selectAt(event.x, event.y, extend = true)
+            }
+            true
+        }
+    }
+
+    @SuppressLint("ClickableViewAccessibility") // A drag has no equal for a screen reader; the panel works where it is.
+    private fun dragWith(handle: View) {
+        var lastX = 0f
+        var lastY = 0f
+        handle.setOnTouchListener { _, event ->
+            when (event.actionMasked) {
+                MotionEvent.ACTION_DOWN -> {
+                    lastX = event.rawX
+                    lastY = event.rawY
+                }
+                MotionEvent.ACTION_MOVE -> {
+                    events.onDrag(event.rawX - lastX, event.rawY - lastY)
+                    lastX = event.rawX
+                    lastY = event.rawY
+                }
+                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> events.onDragEnd()
+            }
+            true
+        }
+    }
+
+    private fun toggle(row: View) {
+        row.isVisible = !row.isVisible
+    }
+
+    private fun button(label: String, description: String?, onClick: () -> Unit) = Button(context).apply {
+        text = label
+        isAllCaps = false
+        contentDescription = description ?: label
+        minWidth = dp(44)
+        minimumWidth = dp(44)
+        setOnClickListener { onClick() }
+    }
+
+    private fun wrap() = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
+
+    private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
+}
diff --git a/app/src/main/kotlin/space/subread/overlay/Store.kt b/app/src/main/kotlin/space/subread/overlay/Store.kt
new file mode 100644
index 0000000..b243d2e
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/overlay/Store.kt
@@ -0,0 +1,69 @@
+package space.subread.overlay
+
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import androidx.core.content.edit
+import androidx.core.net.toUri
+
+/** What the user chose. It stays when the app stops. */
+class Store(context: Context) {
+
+    private val prefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE)
+
+    var subtitles: Uri?
+        get() = prefs.getString("subtitles", null)?.toUri()
+        set(value) = prefs.edit {
+            putString("subtitles", value?.toString())
+            // The offset belongs to one file and its media. Another file starts at zero.
+            putLong("offset", 0)
+        }
+
+    var subtitlesName: String?
+        get() = prefs.getString("subtitles_name", null)
+        set(value) = prefs.edit { putString("subtitles_name", value) }
+
+    var offsetMs: Long
+        get() = prefs.getLong("offset", 0)
+        set(value) = prefs.edit { putLong("offset", value) }
+
+    var textSizeSp: Float
+        get() = prefs.getFloat("text_size", 22f)
+        set(value) = prefs.edit { putFloat("text_size", value.coerceIn(12f, 60f)) }
+
+    /** Where the panel is, in pixels from the top left of the screen. */
+    var x: Int
+        get() = prefs.getInt("x", 0)
+        set(value) = prefs.edit { putInt("x", value) }
+
+    var y: Int
+        get() = prefs.getInt("y", 200)
+        set(value) = prefs.edit { putInt("y", value) }
+
+    /** True when the user wants the panel on the screen. The listener shows it again after a restart. */
+    var shown: Boolean
+        get() = prefs.getBoolean("shown", false)
+        set(value) = prefs.edit { putBoolean("shown", value) }
+
+    /** The app that gets the word. Null: Android asks each time. */
+    var dictionary: ComponentName?
+        get() = prefs.getString("dictionary", null)?.let(ComponentName::unflattenFromString)
+        set(value) = prefs.edit { putString("dictionary", value?.flattenToString()) }
+}
+
+/** Sends a word to a dictionary, a translator or a flash card app. */
+object Lookup {
+
+    /** The intent that each app with "process text" in its manifest takes. It is what a text selection menu sends. */
+    fun probe(): Intent = Intent(Intent.ACTION_PROCESS_TEXT).setType("text/plain")
+
+    fun intent(word: String, chosen: ComponentName?): Intent {
+        val send = probe()
+            .putExtra(Intent.EXTRA_PROCESS_TEXT, word)
+            .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, true)
+        val target = if (chosen != null) send.setComponent(chosen) else Intent.createChooser(send, null)
+        // The panel is not an activity.
+        return target.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+    }
+}
diff --git a/app/src/main/kotlin/space/subread/overlay/Words.kt b/app/src/main/kotlin/space/subread/overlay/Words.kt
new file mode 100644
index 0000000..92c9493
--- /dev/null
+++ b/app/src/main/kotlin/space/subread/overlay/Words.kt
@@ -0,0 +1,32 @@
+package space.subread.overlay
+
+import android.icu.text.BreakIterator
+
+/** Finds the word under a finger. */
+object Words {
+
+    /**
+     * The range of the word of [text] that has the character at [offset]; null on a space or a
+     * punctuation mark.
+     *
+     * ICU cuts Japanese, Chinese and Thai with a dictionary, and other scripts at spaces and
+     * punctuation. The cut is a good first try, not a parse: the user can drag to make the
+     * selection longer.
+     */
+    fun at(text: CharSequence, offset: Int): IntRange? {
+        if (offset !in text.indices) return null
+        val words = BreakIterator.getWordInstance()
+        words.setText(text.toString())
+        val end = words.following(offset)
+        if (end == BreakIterator.DONE) return null
+        val isWord = words.ruleStatus != BreakIterator.WORD_NONE
+        val start = words.previous()
+        return if (isWord && start != BreakIterator.DONE) start until end else null
+    }
+
+    /** The range from the word at [anchor] to the word at [offset], in the order of the text. */
+    fun between(text: CharSequence, anchor: IntRange, offset: Int): IntRange {
+        val other = at(text, offset) ?: return anchor
+        return minOf(anchor.first, other.first)..maxOf(anchor.last, other.last)
+    }
+}
diff --git a/app/src/main/res/drawable/icon.xml b/app/src/main/res/drawable/icon.xml
new file mode 100644
index 0000000..304e040
--- /dev/null
+++ b/app/src/main/res/drawable/icon.xml
@@ -0,0 +1,8 @@
+<?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" />
+    <path android:fillColor="#111111" android:pathData="M18,60h72v24h-72z" />
+    <path android:fillColor="#FFFFFF" android:pathData="M26,68h34v8h-34z M66,68h16v8h-16z" />
+    <path android:fillColor="#111111" android:pathData="M44,24l24,14l-24,14z" />
+</vector>
diff --git a/app/src/main/res/drawable/panel.xml b/app/src/main/res/drawable/panel.xml
new file mode 100644
index 0000000..b5c8660
--- /dev/null
+++ b/app/src/main/res/drawable/panel.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:radius="6dp" />
+</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..c4cbfd4
--- /dev/null
+++ b/app/src/main/res/values/strings.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="app_name">SubRead Overlay</string>
+    <string name="listener_label">SubRead Overlay: position of the media player</string>
+
+    <string name="about">Shows the lines of a subtitle file (.srt) over the app that plays the audiobook or the video: Voice, VLC, mpv, YouTube, a podcast app. The line follows the position of the player. Tap a word to select it, drag to select more, then send it to a dictionary.</string>
+    <string name="privacy">This app has no network permission. Nothing leaves the device.</string>
+
+    <string name="step_overlay">1. Show over other apps</string>
+    <string name="step_overlay_why">Android must allow the subtitle panel on top of the media player.</string>
+    <string name="step_listener">2. Read the position of the media player</string>
+    <string name="step_listener_why">Android gives the position of other apps only to an app with notification access. SubRead Overlay uses this access for the media position, the speed and play or pause. It does not read, keep or send a notification.</string>
+    <string name="step_file">3. Subtitle file</string>
+    <string name="step_file_none">No file. Only .srt for now.</string>
+    <plurals name="step_file_cues">
+        <item quantity="one">%1$s, %2$d line</item>
+        <item quantity="other">%1$s, %2$d lines</item>
+    </plurals>
+    <string name="step_dictionary">4. Dictionary for \"Look up\"</string>
+    <string name="dictionary_ask">Ask each time</string>
+    <string name="dictionary_none">No app on this device takes a selected text. Install a dictionary that has an entry in the text selection menu.</string>
+    <string name="step_size">5. Text size</string>
+    <string name="allowed">Allowed</string>
+    <string name="allow">Allow</string>
+    <string name="choose">Choose</string>
+    <string name="show">Show the subtitles</string>
+    <string name="hide">Hide the subtitles</string>
+    <string name="need_both">Allow steps 1 and 2 first.</string>
+    <string name="listener_starting">Android starts the listener. Try again in a moment.</string>
+
+    <string name="status_no_file">Choose a subtitle file in SubRead Overlay.</string>
+    <string name="status_empty_file">The subtitle file has no lines that the app can read.</string>
+    <string name="status_no_player">No media player. Start the audiobook or the video.</string>
+    <string name="status_before_first_line">Before the first line.</string>
+    <string name="no_dictionary">No app took the word.</string>
+
+    <string name="make_subtitles">No .srt for your audiobook? SubRead makes it from the audiobook and its ebook.</string>
+    <string name="make_subtitles_action">Open subread.space</string>
+    <string name="donate">Support the work on Ko-fi</string>
+</resources>
diff --git a/build.gradle.kts b/build.gradle.kts
new file mode 100644
index 0000000..6ea42bf
--- /dev/null
+++ b/build.gradle.kts
@@ -0,0 +1,5 @@
+// Plugin versions live in gradle/libs.versions.toml; each module applies its own.
+plugins {
+    alias(libs.plugins.kotlin.jvm) apply false
+    alias(libs.plugins.android.application) apply false
+}
diff --git a/core/build.gradle.kts b/core/build.gradle.kts
new file mode 100644
index 0000000..8ac7ac0
--- /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 timing 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 replaces loops over java.util.Random written by hand: 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/overlay/core/CueIndex.kt b/core/src/main/kotlin/space/subread/overlay/core/CueIndex.kt
new file mode 100644
index 0000000..509bcd2
--- /dev/null
+++ b/core/src/main/kotlin/space/subread/overlay/core/CueIndex.kt
@@ -0,0 +1,38 @@
+package space.subread.overlay.core
+
+/**
+ * Finds the line to show for a position in the media.
+ *
+ * The line stays on the screen until the next line starts, also in the silence after its end
+ * time. A reader who looks a word up needs the line to stay; an empty overlay helps nobody.
+ */
+class CueIndex(cues: List<Cue>) {
+
+    val cues: List<Cue> = cues.sortedBy { it.startMs }
+    private val starts = LongArray(this.cues.size) { this.cues[it].startMs }
+
+    val size: Int get() = cues.size
+
+    /** The index of the last cue that starts at or before [positionMs]; -1 before the first cue. */
+    fun indexAt(positionMs: Long): Int {
+        var low = 0
+        var high = starts.lastIndex
+        var found = -1
+        while (low <= high) {
+            val mid = (low + high) ushr 1
+            if (starts[mid] <= positionMs) {
+                found = mid
+                low = mid + 1
+            } else {
+                high = mid - 1
+            }
+        }
+        return found
+    }
+
+    /** The position at which another line comes on after [positionMs]; null after the last cue. */
+    fun nextChangeAfter(positionMs: Long): Long? {
+        val next = indexAt(positionMs) + 1
+        return if (next < starts.size) starts[next] else null
+    }
+}
diff --git a/core/src/main/kotlin/space/subread/overlay/core/PlayClock.kt b/core/src/main/kotlin/space/subread/overlay/core/PlayClock.kt
new file mode 100644
index 0000000..c2fd381
--- /dev/null
+++ b/core/src/main/kotlin/space/subread/overlay/core/PlayClock.kt
@@ -0,0 +1,30 @@
+package space.subread.overlay.core
+
+/**
+ * What a media player said about its position, and when it said it.
+ *
+ * A player does not report each millisecond. It reports a position, the time of the report on
+ * the clock of the device, and the speed. The position now is computed from these three.
+ */
+data class PlayClock(
+    val positionMs: Long,
+    /** The time of the report, on the same clock as the `nowMs` parameters. */
+    val reportedAtMs: Long,
+    val speed: Float,
+    val playing: Boolean,
+) {
+    /** The position in the media at [nowMs]. */
+    fun positionAt(nowMs: Long): Long =
+        if (!playing) positionMs else positionMs + ((nowMs - reportedAtMs) * speed.toDouble()).toLong()
+
+    /**
+     * How long to wait, on the clock of the device, until the media is at [targetMs].
+     * Null when the media does not move forward, or is already there.
+     */
+    fun waitUntil(targetMs: Long, nowMs: Long): Long? {
+        if (!playing || speed <= 0f) return null
+        val left = targetMs - positionAt(nowMs)
+        if (left <= 0) return null
+        return Math.ceil(left / speed.toDouble()).toLong()
+    }
+}
diff --git a/core/src/main/kotlin/space/subread/overlay/core/Srt.kt b/core/src/main/kotlin/space/subread/overlay/core/Srt.kt
new file mode 100644
index 0000000..d3d3a4d
--- /dev/null
+++ b/core/src/main/kotlin/space/subread/overlay/core/Srt.kt
@@ -0,0 +1,47 @@
+package space.subread.overlay.core
+
+/** One subtitle line. The times are milliseconds on the clock of the media file. */
+data class Cue(val startMs: Long, val endMs: Long, val text: String)
+
+/**
+ * Reads SubRip (`.srt`) text.
+ *
+ * The reader is lenient: a block without a valid time line is skipped and the rest of the file
+ * is kept. Subtitle files from the wild have stray numbers, comments and broken blocks.
+ */
+object Srt {
+
+    private val TIMES = Regex(
+        """(\d{1,3}):(\d{2}):(\d{2})[.,](\d{1,3})\s*-->\s*(\d{1,3}):(\d{2}):(\d{2})[.,](\d{1,3})""",
+    )
+    private val TAG = Regex("""<[^>]+>|\{\\[^}]*\}""")
+
+    /**
+     * The cues of [content], sorted by start time.
+     *
+     * Accepts a byte order mark, CRLF, CR or LF line ends, and `.` or `,` before the milliseconds.
+     * Removes format tags (`<i>`, `{\an8}`): the overlay shows plain text.
+     */
+    fun parse(content: String): List<Cue> =
+        content.removePrefix("\uFEFF")
+            .replace("\r\n", "\n").replace('\r', '\n')
+            .split(Regex("\n\\s*\n"))
+            .mapNotNull(::block)
+            .sortedBy { it.startMs }
+
+    private fun block(block: String): Cue? {
+        val lines = block.lines().map { it.trim() }.filter { it.isNotEmpty() }
+        val at = lines.indexOfFirst { TIMES.containsMatchIn(it) }
+        if (at == -1) return null
+        val g = TIMES.find(lines[at])!!.groupValues
+        val start = millis(g[1], g[2], g[3], g[4])
+        val end = millis(g[5], g[6], g[7], g[8])
+        val text = lines.drop(at + 1).joinToString("\n") { it.replace(TAG, "") }.trim()
+        if (end <= start || text.isEmpty()) return null
+        return Cue(start, end, text)
+    }
+
+    private fun millis(h: String, m: String, s: String, fraction: String): Long =
+        h.toLong() * 3_600_000 + m.toLong() * 60_000 + s.toLong() * 1_000 +
+            fraction.padEnd(3, '0').take(3).toLong()
+}
diff --git a/core/src/test/kotlin/space/subread/overlay/core/CoreTest.kt b/core/src/test/kotlin/space/subread/overlay/core/CoreTest.kt
new file mode 100644
index 0000000..ef1d200
--- /dev/null
+++ b/core/src/test/kotlin/space/subread/overlay/core/CoreTest.kt
@@ -0,0 +1,146 @@
+package space.subread.overlay.core
+
+import io.kotest.property.Arb
+import io.kotest.property.arbitrary.boolean
+import io.kotest.property.arbitrary.float
+import io.kotest.property.arbitrary.int
+import io.kotest.property.arbitrary.list
+import io.kotest.property.arbitrary.long
+import io.kotest.property.arbitrary.map
+import io.kotest.property.arbitrary.stringPattern
+import io.kotest.property.checkAll
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class SrtTest {
+
+    private fun stamp(ms: Long) =
+        "%02d:%02d:%02d,%03d".format(ms / 3_600_000, ms / 60_000 % 60, ms / 1_000 % 60, ms % 1_000)
+
+    private fun write(cues: List<Cue>) = cues.withIndex().joinToString("\n\n") { (i, c) ->
+        "${i + 1}\n${stamp(c.startMs)} --> ${stamp(c.endMs)}\n${c.text}"
+    }
+
+    /** Cues that do not share a start time, so that the sorted order is one order only. */
+    private val cues = Arb.list(
+        Arb.int(1..20_000).map { it.toLong() },
+        0..40,
+    ).map { gaps ->
+        var at = 0L
+        gaps.mapIndexed { i, gap ->
+            at += gap
+            Cue(at, at + 1 + gap, "line $i\nsecond row")
+        }
+    }
+
+    @Test
+    fun whatIsWrittenIsReadBack(): Unit = runBlocking {
+        checkAll(cues) { list ->
+            assertEquals(list, Srt.parse(write(list)))
+            assertEquals(list, Srt.parse("\uFEFF" + write(list).replace("\n", "\r\n")))
+        }
+    }
+
+    @Test
+    fun noTextMakesTheReaderFail(): Unit = runBlocking {
+        checkAll(Arb.stringPattern("[0-9a-z:>,\\- \n]{0,200}")) { junk -> Srt.parse(junk) }
+    }
+
+    @Test
+    fun aBrokenBlockIsSkippedAndTheRestIsKept() {
+        val text = """
+            1
+            00:00:01.5 --> 00:00:02,000
+            <i>first</i>
+
+            this is not a cue
+
+            3
+            00:00:05,000 --> 00:00:04,000
+            ends before it starts
+
+            00:00:09,000 --> 00:00:10,000
+            {\an8}no number
+
+            1:00:00,000 --> 100:00:00,000
+            {Japanese 女のいない男たち}
+        """.trimIndent()
+        assertEquals(
+            listOf(
+                Cue(1_500, 2_000, "first"),
+                Cue(9_000, 10_000, "no number"),
+                Cue(3_600_000, 360_000_000, "{Japanese 女のいない男たち}"),
+            ),
+            Srt.parse(text),
+        )
+    }
+}
+
+class CueIndexTest {
+
+    private val starts = Arb.list(Arb.long(0L..100_000L), 0..60)
+
+    @Test
+    fun theSameAnswerAsALookAtEachCue(): Unit = runBlocking {
+        checkAll(starts, Arb.long(-10L..100_010L)) { list, position ->
+            val index = CueIndex(list.map { Cue(it, it + 500, "x") })
+            val sorted = list.sorted()
+            assertEquals(sorted.indexOfLast { it <= position }, index.indexAt(position))
+            assertEquals(sorted.firstOrNull { it > position }, index.nextChangeAfter(position))
+        }
+    }
+
+    @Test
+    fun theLineStaysUntilTheNextLineStarts() {
+        val index = CueIndex(listOf(Cue(1_000, 2_000, "a"), Cue(10_000, 11_000, "b")))
+        assertEquals(-1, index.indexAt(999))
+        assertEquals(0, index.indexAt(1_000))
+        assertEquals("the silence after the end of the line", 0, index.indexAt(9_999))
+        assertEquals(1, index.indexAt(10_000))
+        assertEquals(1, index.indexAt(Long.MAX_VALUE))
+        assertNull(index.nextChangeAfter(10_000))
+        assertEquals(-1, CueIndex(emptyList()).indexAt(5))
+    }
+}
+
+class PlayClockTest {
+
+    @Test
+    fun aPausedPlayerDoesNotMove(): Unit = runBlocking {
+        checkAll(Arb.long(0L..1_000_000L), Arb.long(0L..1_000_000L)) { position, later ->
+            val clock = PlayClock(position, 0, 1f, playing = false)
+            assertEquals(position, clock.positionAt(later))
+            assertNull(clock.waitUntil(position + 1, later))
+        }
+    }
+
+    @Test
+    fun afterTheWaitTheMediaIsAtTheTarget(): Unit = runBlocking {
+        checkAll(
+            Arb.long(0L..36_000_000L),
+            Arb.long(0L..10_000_000L),
+            Arb.float(0.25f..4f),
+            Arb.long(1L..600_000L),
+            Arb.boolean(),
+        ) { position, now, speed, ahead, reportedLate ->
+            val clock = PlayClock(position, if (reportedLate) now else 0, speed, playing = true)
+            val target = clock.positionAt(now) + ahead
+            val wait = clock.waitUntil(target, now)!!
+            // Not early, and late by less than one step of the device clock at this speed.
+            assertTrue("early", clock.positionAt(now + wait) >= target - 1)
+            assertTrue("late", clock.positionAt(now + wait) <= target + speed.toLong() + 1)
+        }
+    }
+
+    @Test
+    fun speedScalesTheTime() {
+        val clock = PlayClock(60_000, reportedAtMs = 1_000, speed = 2f, playing = true)
+        assertEquals(60_000, clock.positionAt(1_000))
+        assertEquals(64_000, clock.positionAt(3_000))
+        assertEquals(500L, clock.waitUntil(65_000, 3_000))
+        assertNull("already past", clock.waitUntil(63_000, 3_000))
+    }
+}
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..354f85c
--- /dev/null
+++ b/gradle/libs.versions.toml
@@ -0,0 +1,23 @@
+[versions]
+agp = "9.2.0"
+kotlin = "2.3.21"
+coreKtx = "1.16.0"
+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" }
+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..802cb2a
--- /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 = "SubReadOverlay"
+
+// Plain Kotlin: the subtitle file, the line for a position, the clock. Builds with a JDK alone.
+include(":core")
+include(":app")