Compare commits
82
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79cd9f3804
|
||
|
|
08a720465e
|
||
|
|
bac89b5e68
|
||
|
|
5e5e63353a
|
||
|
|
660ff90b3a
|
||
|
|
9610a8a9d8
|
||
|
|
1f596af56d
|
||
|
|
635982a4f8
|
||
|
|
5d9e367992
|
||
|
|
72657ba157
|
||
|
|
37574292cd
|
||
|
|
a9bdfcc18a
|
||
|
|
5256959a11
|
||
|
|
c4813831f5
|
||
|
|
6e08795a5c
|
||
|
|
385f2f7f5d
|
||
|
|
eeba64b1c7
|
||
|
|
a249b516fd
|
||
|
|
7a75633ea1
|
||
|
|
7fcdecf1c8
|
||
|
|
7971676344
|
||
|
|
97ba7f6a29
|
||
|
|
e485530e46
|
||
|
|
1659a79848
|
||
|
|
dec2225a9c
|
||
|
|
5d1e36868c
|
||
|
|
6e24f6f370
|
||
|
|
536f71a627
|
||
|
|
ceaf8ea91f
|
||
|
|
c38582f600
|
||
|
|
7d49b8d94b
|
||
|
|
2375affca8
|
||
|
|
df20788d7f
|
||
|
|
8e84f0d53d
|
||
|
|
4b4fe46725
|
||
|
|
8a486b7228
|
||
|
|
f04a670227
|
||
|
|
efba3aacf4
|
||
|
|
1d3154cefa
|
||
|
|
979a504600
|
||
|
|
c0dd0b5a50
|
||
|
|
5689994037
|
||
|
|
4344b35a27
|
||
|
|
6540d160df
|
||
|
|
a4a5c5dba1
|
||
|
|
cdb6a35371
|
||
|
|
5e45293462
|
||
|
|
7ca44ef5e2
|
||
|
|
2f43b94e56
|
||
|
|
472aff6b22
|
||
|
|
f9cca74af5
|
||
|
|
af290cd7d5
|
||
|
|
24669b7cd6
|
||
|
|
80ba7f70b9
|
||
|
|
613eba4154
|
||
|
|
ca1ace2987
|
||
|
|
dcd5adf491
|
||
|
|
adc1c4fe3e
|
||
|
|
118b2aa764
|
||
|
|
694e7f46d7
|
||
|
|
d30b74e1a4
|
||
|
|
5fcc158763
|
||
|
|
649cb526de
|
||
|
|
3e15900521
|
||
|
|
0437f802a4
|
||
|
|
e35bf3004c
|
||
|
|
a30075c8f3
|
||
|
|
f2a2acf996
|
||
|
|
6a05f56e7c
|
||
|
|
e1d99f3f0a
|
||
|
|
3046ad154a
|
||
|
|
374574b9ce
|
||
|
|
2d38ccd321
|
||
|
|
f816919071
|
||
|
|
9906554d09
|
||
|
|
9ca27cee01
|
||
|
|
dc642c62b9
|
||
|
|
2080f0b67e
|
||
|
|
9592fbeeb4
|
||
|
|
9976186599
|
||
|
|
d46e7aa548
|
||
|
|
77e1539e8f
|
No files matched your search
@@ -37,26 +37,57 @@ jobs:
|
||||
echo "369ad2b789f95a011f807e1fcb690ccef80bd7cd014fd139e73ae82dcc0baeab ktlint.jar" | sha256sum -c
|
||||
java -jar ktlint.jar "app/src/**/*.kt" "*.kts" "app/*.kts"
|
||||
|
||||
# The wake-word engine and model for the full build, hash-pinned (never in the repository).
|
||||
- name: Wake-word engine (hash-pinned)
|
||||
run: python3 scripts/fetch-wakeword.py
|
||||
|
||||
# The wake phrases' token pieces are generated from the model's own tokenizer (bpe.model,
|
||||
# fetched above); the committed table must be what it gives.
|
||||
- name: Wake phrases match the model's tokenizer
|
||||
run: |
|
||||
python3 -m venv "$RUNNER_TEMP/wake"
|
||||
"$RUNNER_TEMP/wake/bin/pip" install --quiet --require-hashes --only-binary :all: -r scripts/wake-requirements.txt
|
||||
"$RUNNER_TEMP/wake/bin/python" scripts/gen-wake-phrases.py --check
|
||||
|
||||
- uses: gradle/actions/wrapper-validation@v4
|
||||
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
|
||||
- name: Unit tests and both builds
|
||||
run: ./gradlew --no-daemon testFullDebugUnitTest assembleFullDebug assembleFdroidDebug
|
||||
- name: Unit tests and the three builds
|
||||
run: >
|
||||
./gradlew --no-daemon testFullStandardDebugUnitTest
|
||||
assembleFullStandardDebug assembleFullNotificationsDebug assembleFdroidStandardDebug
|
||||
|
||||
# The files themselves: only the notifications build declares a notification listener, the
|
||||
# wake-word model is stored uncompressed, the F-Droid build has no engine.
|
||||
- name: What the APKs declare
|
||||
run: |
|
||||
scripts/check-apk.sh app/build/outputs/apk/fullStandard/debug/app-full-standard-debug.apk standard
|
||||
scripts/check-apk.sh app/build/outputs/apk/fullNotifications/debug/app-full-notifications-debug.apk notifications
|
||||
scripts/check-apk.sh app/build/outputs/apk/fdroidStandard/debug/app-fdroid-standard-debug.apk fdroid
|
||||
|
||||
# A release as the release workflow builds it, unsigned: shrunk by R8, and without the
|
||||
# emulator's x86_64 libraries. Found here rather than at a tag.
|
||||
- name: The release build's shape
|
||||
run: |
|
||||
./gradlew --no-daemon assembleFullStandardRelease
|
||||
scripts/check-apk.sh "$(ls app/build/outputs/apk/fullStandard/release/*.apk)" standard release
|
||||
|
||||
- name: Android lint (report only, for now)
|
||||
run: ./gradlew --no-daemon lintFullDebug
|
||||
run: ./gradlew --no-daemon lintFullStandardDebug
|
||||
continue-on-error: true
|
||||
|
||||
# The test build a tester installs (Actions › this run › Artifacts): debug-signed with the
|
||||
# repository's public test key, so each one installs over the last. `full` is the one to
|
||||
# use; `fdroid` is the same app without the updater.
|
||||
# repository's public test key, so each one installs over the last. The plain one is the
|
||||
# one to use; `-notifications` is the same app with the notification listener (it installs
|
||||
# over the plain one and back); `-fdroid` is the app without the updater and the wake word.
|
||||
- name: Name the test builds
|
||||
run: |
|
||||
mkdir test-builds
|
||||
short="${GITHUB_SHA::7}"
|
||||
cp app/build/outputs/apk/full/debug/app-full-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short.apk"
|
||||
cp app/build/outputs/apk/fdroid/debug/app-fdroid-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short-fdroid.apk"
|
||||
cp app/build/outputs/apk/fullStandard/debug/app-full-standard-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short.apk"
|
||||
cp app/build/outputs/apk/fullNotifications/debug/app-full-notifications-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short-notifications.apk"
|
||||
cp app/build/outputs/apk/fdroidStandard/debug/app-fdroid-standard-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short-fdroid.apk"
|
||||
(cd test-builds && sha256sum *.apk > SHA256SUMS)
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
name: Release
|
||||
|
||||
# A signed tag `vX.Y.Z` builds both flavours, signed with the release key from the secrets,
|
||||
# and publishes them with SHA256SUMS as the GitHub Release. The release notes are the tag's
|
||||
# A signed tag `vX.Y.Z` builds the three APKs, signed with the release key from the secrets,
|
||||
# and publishes them with SHA256SUMS as the GitHub Release: the standard one, `-notifications`
|
||||
# (the same app, id and key, plus the notification listener) and `-fdroid`. The release notes are the tag's
|
||||
# message. The key never touches the repository: it is written to a temporary file here and
|
||||
# deleted with the runner.
|
||||
on:
|
||||
@@ -43,6 +44,10 @@ jobs:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
# The wake-word engine and model for the full build, hash-pinned (never in the repository).
|
||||
- name: Wake-word engine (hash-pinned)
|
||||
run: python3 scripts/fetch-wakeword.py
|
||||
|
||||
- uses: gradle/actions/wrapper-validation@v4
|
||||
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
@@ -57,14 +62,20 @@ jobs:
|
||||
[ -n "$KEYSTORE_B64" ] || { echo "no release key in the secrets" >&2; exit 1; }
|
||||
export LEMBAS_KEYSTORE="$RUNNER_TEMP/release.jks"
|
||||
echo "$KEYSTORE_B64" | base64 -d > "$LEMBAS_KEYSTORE"
|
||||
./gradlew --no-daemon testFullReleaseUnitTest assembleFullRelease assembleFdroidRelease
|
||||
./gradlew --no-daemon testFullStandardReleaseUnitTest assembleFullStandardRelease assembleFullNotificationsRelease assembleFdroidStandardRelease
|
||||
rm -f "$LEMBAS_KEYSTORE"
|
||||
|
||||
- name: Name the files and sum them
|
||||
run: |
|
||||
mkdir dist
|
||||
cp app/build/outputs/apk/full/release/app-full-release.apk "dist/llembas-android-$VERSION.apk"
|
||||
cp app/build/outputs/apk/fdroid/release/app-fdroid-release.apk "dist/llembas-android-$VERSION-fdroid.apk"
|
||||
cp app/build/outputs/apk/fullStandard/release/app-full-standard-release.apk "dist/llembas-android-$VERSION.apk"
|
||||
cp app/build/outputs/apk/fullNotifications/release/app-full-notifications-release.apk "dist/llembas-android-$VERSION-notifications.apk"
|
||||
cp app/build/outputs/apk/fdroidStandard/release/app-fdroid-standard-release.apk "dist/llembas-android-$VERSION-fdroid.apk"
|
||||
# What is about to be published, checked on the files: the listener only in
|
||||
# -notifications, the model stored, no x86_64 library.
|
||||
scripts/check-apk.sh "dist/llembas-android-$VERSION.apk" standard release
|
||||
scripts/check-apk.sh "dist/llembas-android-$VERSION-notifications.apk" notifications release
|
||||
scripts/check-apk.sh "dist/llembas-android-$VERSION-fdroid.apk" fdroid release
|
||||
{ echo "# llembas-android $VERSION"; (cd dist && sha256sum *.apk); } > SHA256SUMS
|
||||
mv SHA256SUMS dist/
|
||||
|
||||
|
||||
@@ -16,3 +16,6 @@ local.properties
|
||||
.kotlin/
|
||||
# Python
|
||||
__pycache__/
|
||||
# The wake-word engine and model: fetched by scripts/fetch-wakeword.py, never committed
|
||||
/app/libs/
|
||||
/app/src/full/assets/wakeword/
|
||||
+557
@@ -3,6 +3,563 @@
|
||||
What changed in each release of LLeMbas for Android. Versions follow SemVer; until 1.0.0 the app
|
||||
is in alpha and releases come off `main`.
|
||||
|
||||
## [1.0.0-beta.15] — 2026-11-24
|
||||
|
||||
What is said here of shown files and of an edit's diff needs an instance newer than LLeMbas
|
||||
2.0.0-beta.18. On an older one the app behaves as before.
|
||||
|
||||
### Added
|
||||
|
||||
- **A file an agent shows is in the chat, whatever it is.** When an agent puts a file in front
|
||||
of you that is not text -- a screenshot it took, a recording, a report -- the reply holds it
|
||||
where generated media is: a picture is drawn, with its name under it; sound and video have
|
||||
Play and the app's own player; a PDF has Open, which lays its pages out over the chat. A 3D
|
||||
model, an archive, a text file that came this way and any other file are a row with the
|
||||
file's name, what it is in words and its size. A kind the app has not heard of is a "File",
|
||||
never an empty place. Every one of them has Open in Files, Download, Share and Open with.
|
||||
Whether a file is shown does not depend on what the model itself can read.
|
||||
- **An edit's approval card shows what would change.** Where a linked computer asks before an
|
||||
edit, the card lists each file with the lines that go and the lines that come, marked by a
|
||||
sign and by colour, with a little unchanged text around them; a new file and a deleted one
|
||||
say so. Long lines scroll sideways inside their own box; a long change is folded to its first
|
||||
lines with "Show all". Both texts are drawn as plain text. Allow and Deny are as they were.
|
||||
A character that cannot be seen or that changes the direction of a line, in a line or in a
|
||||
path, is written as its code point (`<U+202E>`), so what the card shows is what is written. A
|
||||
file whose line endings change says so once instead of showing every line twice. A very long
|
||||
change is compared only at its beginning and says so, and is worked out beside the screen,
|
||||
not in it. The call's arguments stay in view when there is no change to show.
|
||||
|
||||
### Changed
|
||||
|
||||
- **A picture in a chat is fetched only while the app is in front of an unlocked phone**, like
|
||||
every other file of the account; one that comes into view behind the lock waits. The
|
||||
assistant's sheet counts as the app in front, so a picture in it is fetched as before.
|
||||
- **"Open with" offers a file as what it is.** The type handed to the other app is read from the
|
||||
file's own first bytes, or from its name's extension where the bytes carry no mark, and no
|
||||
longer taken from what the instance said of it.
|
||||
- Pinned to the server's `dev` at `809b87b`. A linked computer's files and the editor's two
|
||||
models are read from the instance and not shown anywhere yet: this app has no browser for a
|
||||
computer's files and no screen for the editor's settings.
|
||||
|
||||
- **The launcher icon is the app's own**: the LLeMbas leaf with a small phone beside it, so the app
|
||||
is told apart from the other LLeMbas products. The notification icon stays the leaf.
|
||||
|
||||
## [1.0.0-beta.14] — 2026-11-24
|
||||
|
||||
What is said here of replies that start by themselves needs an instance newer than LLeMbas
|
||||
2.0.0-beta.17. On an older one the app behaves as before.
|
||||
|
||||
### Added
|
||||
|
||||
- **An open chat shows a reply it did not ask for, as it is written.** When a subagent finishes
|
||||
and the main agent answers, when a scheduled task's result or a finished generation wakes the
|
||||
chat, or when the linked computer starts a turn itself, the reply appears and is written in
|
||||
front of you, with its tools and cards, instead of only after the chat was opened again.
|
||||
Coming back to the app reads the chat once, for what happened meanwhile. Such a reply is
|
||||
followed only while the app is in front of an unlocked phone: locked or in the background the
|
||||
app lets it go and asks the instance nothing, and on your return it picks up where the chat
|
||||
is then. A reply you asked for yourself goes on being received, as before.
|
||||
- **The list of chats moves by itself.** While the drawer is open, a chat a reply starts in
|
||||
goes to the top and shows its dot, and the dot of a reply being written goes when the reply
|
||||
ends, without the drawer being closed and opened.
|
||||
|
||||
- **A message that waits can be sent now or discarded.** Under a message that has not been
|
||||
given to a model yet -- queued behind a reply, or waiting on a linked computer -- there are
|
||||
"Send now" and "Discard", as on the web page. Send now starts its reply, which is written in
|
||||
front of you like any you asked for; Discard asks once and takes the message away. Where the
|
||||
instance refuses (a reply is still being written; the message is no longer waiting), it says
|
||||
so in its own words and the chat is read again. A waiting message is not offered Edit: the
|
||||
instance refuses that. Needs an instance that has these two actions.
|
||||
|
||||
### Changed
|
||||
|
||||
- **A waiting message says how it waits**, in the instance's words. One of which it is not
|
||||
known whether it reached the linked computer says so, instead of looking queued: the
|
||||
instance does not send it by itself. One the computer holds says that the computer has it
|
||||
and takes it in with its next turn.
|
||||
- **A turn the linked computer started is a quiet note**, as a schedule's line is: it never
|
||||
looks like something you typed.
|
||||
- In an agent chat, a finished reply that holds nothing, after such a turn, says "The reply to
|
||||
this was not recorded." in one line. Older instances left a few of these as blank rows.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The chat keeps its place.** At the end of the chat you stay at the end; anywhere else, what
|
||||
you are reading does not move.
|
||||
- Reading the chat again (after an edit, a queued message, a reply that woke the chat) no
|
||||
longer takes away the earlier messages you had loaded, and with them the row you were
|
||||
reading.
|
||||
- The app's own scroll to the end can no longer be taken for you scrolling away, which
|
||||
stopped the chat from following a reply although you had not touched it. The assistant's
|
||||
sheet has the same fix.
|
||||
- Scrolling up with a mouse wheel, a keyboard or a screen reader while a reply arrives no
|
||||
longer throws you back to the end: only a finger used to count as you scrolling.
|
||||
- A reply's foot is as tall while it is written as when it has finished, so the end of a
|
||||
reply no longer changes the height of the page.
|
||||
|
||||
## [1.0.0-beta.13] — 2026-11-19
|
||||
|
||||
For Files, generated media and MCP servers as described here the instance must be newer than
|
||||
LLeMbas 2.0.0-beta.16. On an older one Files lists and shows text as before, and says so where
|
||||
it cannot do more.
|
||||
|
||||
### Added
|
||||
|
||||
- **Files is a file manager.** Upload from the phone (several at once, with progress; a file
|
||||
over the instance's limit is refused in the instance's own words and the others still go),
|
||||
make a folder or a text file, rename, move and copy by walking to the folder rather than
|
||||
typing a path, and delete to the trash. A long press chooses; with several chosen, a bar moves,
|
||||
copies, downloads, shares or deletes them all, and says which the instance refused.
|
||||
- **The trash and a file's versions.** What was deleted can be restored or removed for good,
|
||||
one thing or everything. A file's earlier versions are listed, and any of them can be made
|
||||
the file again without losing the others, or saved to the phone as it was.
|
||||
- **Download, Open with and Share.** A file is saved where you choose in the phone's own
|
||||
"Save to" page; several files or a folder come as one zip. Open with and Share hand another
|
||||
app a copy from the app's private storage, which is deleted an hour later, and at once when
|
||||
you sign out or switch instance. The app asks for no storage permission.
|
||||
- **Text files can be edited.** Markdown, code, plain text, a page's source and a table's text,
|
||||
up to the instance's 1 MB. If the file changed on the instance while you were writing, nothing
|
||||
is written over: you choose Reload or Save anyway. Leaving with unsaved text asks first.
|
||||
- **A viewer for each kind of file.** Pictures, with zoom and pan; PDFs, page by page; sound and
|
||||
video, streamed, with seeking; CSV and TSV as a grid; notebooks as their cells' text; an
|
||||
archive as the list of what is inside it, with nothing unpacked. For 3D models and anything
|
||||
else: what it is, with Download, Open with and Share. A PDF is shown up to 100 MB and 2000
|
||||
pages. An HTML page and an SVG are shown as their source -- the app draws nothing a file
|
||||
could script.
|
||||
- **"Save to Files" in the share sheet.** Something shared from another app can be kept in a
|
||||
folder of your files instead of being sent into a chat; shared text is kept as a note. If a
|
||||
file is refused, Save again goes on from that file and does not send the earlier ones twice.
|
||||
- **The share sheet says what came in.** Each shared file is listed with its name and size
|
||||
before anything is sent, and the instance is asked nothing until you choose what to do.
|
||||
- **What a model makes is shown in the chat.** A picture, a video, a piece of music or a 3D
|
||||
model the instance made has a card in the reply: the picture drawn, video and music with
|
||||
Play, a 3D model as what it is. Each card leads to the file in Files -- where it is now, also
|
||||
after it was renamed or moved -- saves it where you choose, shares it, or opens it with
|
||||
another app.
|
||||
- **A long generation shows how it stands.** A video or a track takes minutes. Its card says
|
||||
what is being made, whether it is waiting or running and for how long, and has Cancel. When
|
||||
it is ready the card becomes the player and the chat says so; when it was not made, the card
|
||||
says why in the instance's own words. Nothing of this is shown over the lock screen, and the
|
||||
app posts no notification about a file.
|
||||
- **Sound and video you attached can be played** from the message they are attached to.
|
||||
- **Settings › MCP servers.** The MCP servers your chats may be offered, how many tools each
|
||||
has and how each is signed in to. One that waits for your sign-in has a button that opens the
|
||||
instance's own sign-in page in the browser; the list is read again when you come back.
|
||||
- **A new folder from inside the folder picker**, when moving, copying or saving a share.
|
||||
- **A table can be shown as its text**, and as a table again.
|
||||
|
||||
### Changed
|
||||
|
||||
- **A new file is never written over another.** The instance now makes a new file only where
|
||||
nothing has that name, and says what is there otherwise.
|
||||
- **Only models you can chat with are offered** in the model lists and for the assistant.
|
||||
- **Nothing new is sent while the phone is locked.** Uploads, downloads and the copies for
|
||||
Share and Open with go one request at a time: when the phone locks or the app is left, the
|
||||
one under way finishes and the rest wait, and go on by themselves when the app is open on an
|
||||
unlocked phone again. The progress dialog says when it is waiting.
|
||||
- **The share sheet takes files only from other apps.** A share that names something of
|
||||
LLeMbas's own storage is left out, and the sheet says so.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A chat on a model two connections serve shows the right connection.** When an instance has
|
||||
the same model on two connections, a chat, a reply and a scheduled task on the second one were
|
||||
shown as being on the first: the title, the tick in the model list, the picture, the thinking
|
||||
control. The instance now says which connection each is on, and the app shows that one. The
|
||||
line under a reply and a scheduled task's model name the connection where two share a name.
|
||||
An instance that does not say it yet is shown as before. A chat or a scheduled task whose
|
||||
connection is no longer offered shows no model rather than another connection's.
|
||||
|
||||
## [1.0.0-beta.12] — 2026-11-18
|
||||
|
||||
For what is new here the instance must be newer than LLeMbas 2.0.0-beta.14; an older one ignores
|
||||
what the app adds and answers as before.
|
||||
|
||||
### Added
|
||||
|
||||
- **Dictation and Read aloud follow the chat's model.** An instance may now give a connection
|
||||
speech models of its own, used for the chats whose model is on that connection. The app says
|
||||
which chat a recording or a reading is for: the chat it is in, or -- before the chat exists --
|
||||
the model chosen for it (in the assistant, the assistant's model). Dictation into another app
|
||||
belongs to no chat and stays on the instance's default. When the chat's own speech model did
|
||||
not answer and the default did, the chat says so once, quietly, naming what answered; the
|
||||
assistant's sheet does not say it, because it may be open over the lock screen. Nothing new
|
||||
is sent while the phone is locked.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A dictation that fails says so.** When the instance refused a recording or could not be
|
||||
reached, the chat's field simply stayed as it was. Now the chat says why.
|
||||
- **A refusal about speech is said in the instance's own words.** A dictation or a reading the
|
||||
instance refused showed "The server answered 502." in the chat and in the assistant; the
|
||||
instance's sentence is shown instead.
|
||||
|
||||
## [1.0.0-beta.11] — 2026-11-18
|
||||
|
||||
Needs LLeMbas 2.0.0-beta.14 for what is new here; with an older instance the app works as before.
|
||||
|
||||
### Added
|
||||
|
||||
- **Choose a folder on your computer instead of typing its path.** A new agent chat's *Folder
|
||||
on the device* opens a picker: the computer's places, then down through its folders and back
|
||||
up -- the back gesture goes up a level and closes at the top. A folder the computer will not
|
||||
open a session in says why and cannot be chosen; a folder you worked in before names the
|
||||
model you last used there. The path can still be typed, and that is what remains when the
|
||||
computer is not linked, does not answer, or runs a LLeMbas CLI too old to list its folders --
|
||||
the picker says which.
|
||||
- **A new agent chat starts on the model you last used in that folder.** Once the computer and
|
||||
the folder are chosen, the model shown is the folder's usual one (the computer remembers it;
|
||||
the app keeps nothing), and it changes when you choose another computer or folder. A model
|
||||
you pick yourself stays picked.
|
||||
- **Scheduled tasks have two types: Chat and Agentic.** The form asks the type first. *Chat*
|
||||
runs on your instance, as tasks always have. *Agentic* runs on one of your computers, in one
|
||||
folder there, as an agent: you choose the computer, the folder (with the picker, or typed),
|
||||
the mode (only those the computer allows), how long an approval waits, a command to watch
|
||||
(the task then runs only when its output changed), and the model -- *The folder's usual
|
||||
model* unless you choose one of your scheduling models. Editing a task says to the instance
|
||||
only what you changed, so a task's words can be put right while its computer is not linked. Agentic can be chosen only while one of your computers
|
||||
accepts scheduled work, and says so otherwise. A task's page shows its type, computer, folder
|
||||
and model; each run says where it ran and when its model was the folder's usual one, your
|
||||
default or the conversation's own.
|
||||
- **Two models with the same name on different connections are told apart.** Where an instance
|
||||
serves one model through two connections, the pickers say *Name · Connection*, and the one
|
||||
you pick is the one used -- in a chat, as the assistant's model, in a scheduled task. A
|
||||
model chosen before this still finds its row.
|
||||
- **`@` in the composer.** Type `@` and a few letters at the end of a message: in a chat the
|
||||
list offers your files, what was attached earlier in the chat and a web address, and a tap
|
||||
attaches it; in an agent chat it offers the files in the chat's folder on the computer, and
|
||||
a tap completes the path for the agent to read.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The badge on Reports is live.** The count of unread reports in the drawer follows the
|
||||
instance while the app is in front -- a report that arrives, or one read on another device,
|
||||
moves it at once. Before, it was read only when the drawer opened.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Two quick taps on *Older* no longer end the app.** The same page of older messages was
|
||||
fetched twice and put above the chat twice. One page is read at a time now, and a message is
|
||||
never added a second time.
|
||||
- **A reply whose stream ends without its last frame no longer disappears.** What had been
|
||||
written vanished until the chat was opened again. The chat is now read again at that point;
|
||||
where it cannot be read, what was written stays as it stood, with its *Stopped* or *Failed*
|
||||
line where the instance had said one.
|
||||
- **Other apps' dictation sends nothing to your instance while the phone is locked.** While
|
||||
LLeMbas is the digital assistant, an app that asks Android's speech recogniser is answered by
|
||||
your instance -- until now also over the lock screen. A locked phone now uses its own
|
||||
on-device recogniser where it has one, and otherwise tells the app that no recogniser is
|
||||
available; a phone that locks while it is listening sends nothing either.
|
||||
- **A thinking block you opened stays open.** It closed by itself when the thinking ended and
|
||||
the words began, and again when the reply finished.
|
||||
- **Edit, Regenerate, Continue and Carry out the plan tell the instance they come from the
|
||||
phone**, as a new message always did, so a reply started that way is also written for an app
|
||||
that draws no pages.
|
||||
- **The chat no longer pulls you away from what you are reading while a reply is written.** The
|
||||
view follows the reply only while you are at the end. Once you scroll up it stays exactly
|
||||
where you are -- a finger on the list ends the following at once -- and scrolling back to the
|
||||
end takes it up again. Before, the next queued turn starting, a transcript read again and a
|
||||
rotation could each throw the view to the end.
|
||||
- **Older messages no longer throw the chat to its end.** Tapping *Older* keeps the message you
|
||||
were at in place, with the older ones above it.
|
||||
- **The keyboard no longer covers the last lines**: opening it at the end of a chat keeps the
|
||||
end in view.
|
||||
- **The assistant's sheet follows the same rule.** It pulled the answer back to its end at every
|
||||
word, also for somebody reading further up.
|
||||
- **A message written on another device no longer throws the chat to its end** while you read
|
||||
further up: only a message sent from this phone does.
|
||||
|
||||
## [1.0.0-beta.10] — 2026-11-13
|
||||
|
||||
### Added
|
||||
|
||||
- **Assistant model** in Settings › Assistant: the model the assistant's new chats start on --
|
||||
*Instance default* (your account's default, as before) or any model of the instance. A large
|
||||
default model is slow to answer a spoken question; a quick one can be chosen for the assistant
|
||||
alone. It holds for every way in: the sheet, the wake word, Share. Picking a model in the
|
||||
sheet still changes it too.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The wake word and the hands-free parts of the voice assistant are marked Experimental** in
|
||||
Settings: the wake word as a whole, and with the assistant *Start listening when the
|
||||
assistant opens* and *Keep a spoken conversation going*. They are new and have been tried on
|
||||
few phones: the wake word may miss the phrase, start by mistake, or hear you and still not
|
||||
open the assistant; listening may stop too early or too late. Typing a question and the
|
||||
microphone button are the parts to rely on.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The wake word with the screen off: the sheet showed for a moment and was gone.** A phone
|
||||
whose screen is off is locked, and a sheet opened over the lock screen asked Android to unlock
|
||||
first and closed itself when that was turned down -- which is what happens when nobody is
|
||||
there to unlock. Opened to listen (the wake word, a headset's button), the sheet now stays up
|
||||
over the lock screen and listens, and Android is asked to unlock once it has heard you: a face
|
||||
or a fingerprint sends the question. Leave it, and it stays until the screen goes off.
|
||||
- **Nothing goes to your instance while the phone is locked.** Not the question, not the
|
||||
recording, not even "which models are there". With Voice input › LLeMbas the question waits on
|
||||
the phone as a recording -- the sheet says *Question heard*, with no words, and **Unlock to
|
||||
send** -- and is written down and asked once you unlock. With Voice input › Phone the phone's
|
||||
own recogniser writes it down (the recording goes wherever that recogniser sends it, as
|
||||
always) and the words are shown while they wait. No answer is shown or spoken over the lock
|
||||
screen, and an answer over the lock screen is not offered.
|
||||
- **A phone that locks while the assistant is open stops there.** The screen going off stops the
|
||||
microphone and the voice at once; a question still being listened to is dropped; an answer is
|
||||
no longer read aloud on a locked phone, a spoken conversation does not go on, and the
|
||||
conversation that was on the sheet is not readable over the lock screen -- nor a failure's
|
||||
words, which may name the instance. The screen stays on while an answer is read aloud.
|
||||
- **Another app can no longer put a question into the assistant.** The
|
||||
sheet's screen has to be startable by Android (the assist action, a headset's button), so any
|
||||
app can start it. A question handed from the assistant's own sheet no longer travels in the
|
||||
intent, where any app could have written one to be asked on your account (or to wait for your
|
||||
next unlock): it stays in the app's memory and the intent carries a one-time ticket. Opening
|
||||
listening, the last chat and turning the screen on are honoured only on intents the app made
|
||||
itself. Android's own headset actions still open it listening, as they must.
|
||||
- The sheet no longer asks its question a second time, or loses the one that waits, when the
|
||||
phone is turned, folded or switches theme while it is up.
|
||||
- Closing the sheet lets go of the microphone at once, also when it was closed in the middle of
|
||||
listening.
|
||||
- Listening no longer runs to the limit after speech into a headset that gates its noise to
|
||||
exact silence, and no longer gives up as "nothing said" on someone who goes straight on after
|
||||
the wake word in a steady voice. The phone's recogniser is not given up on while it reports
|
||||
speech but shows no words yet.
|
||||
- **A new assistant chat could start on the wrong model.** After *Continue the last chat*, *New
|
||||
chat* kept that chat's model instead of going back to the assistant's own; and a question
|
||||
sent the moment the sheet opened, before the instance had said which models it has, went to
|
||||
the instance's default whatever was chosen.
|
||||
|
||||
- **Listening went on and on in a quiet room.** With the instance's speech-to-text the sheet
|
||||
decided "somebody is speaking" and "it is quiet again" by two fixed loudness levels. A phone
|
||||
whose room noise sat above the quiet level never heard a pause, so it listened until the
|
||||
two-minute limit; and words the speech-to-text invented from silence counted as speech. Now
|
||||
the room's own level is measured from the first moment and followed all the time, and speech
|
||||
and quiet are judged against it: nothing said ends after five seconds, a question ends a
|
||||
second and a half after you stop, a click or a knock is not speech, and the limit is one
|
||||
minute. Silence is no longer sent to be written down while you have said nothing.
|
||||
- The phone's own recogniser (Voice input › Phone) is asked for the same pause, and is watched:
|
||||
one that never answers no longer leaves the sheet listening for good.
|
||||
- An app that uses the system's recogniser while LLeMbas is the assistant no longer waits the
|
||||
full fifteen seconds every time: it ends at the pause after speech, or says that nothing was
|
||||
said.
|
||||
|
||||
## [1.0.0-beta.9] — 2026-11-13
|
||||
|
||||
For LLeMbas server 2.0.0-beta.12 or later.
|
||||
|
||||
For LLeMbas server 2.0.0-beta.12 (harness spec 3.8.0); an older instance works as before.
|
||||
|
||||
### Added
|
||||
|
||||
- **Reports.** A scheduled task no longer answers into a chat: it files a report when it has
|
||||
something to tell you, or leaves a line in its history. *Reports* is in the drawer, with a
|
||||
count of the unread. The list has the unread first -- title, the task it came from, when, and
|
||||
a mark where the model called it important; pull to read it again, swipe a row one way to mark
|
||||
it read and the other to delete it (which asks once). A report reads as a page and is marked
|
||||
read when opened; **Share** hands its text to another app; **Reply** continues it as a
|
||||
conversation that stays with the report -- its bar says *Report: …*, Back returns to the
|
||||
report, and it is not among your chats.
|
||||
- **Notify when** on a scheduled task's form: *Every run* (the model writes a report every
|
||||
time, also when nothing was found), *When…* (only when your own words hold; "something needs
|
||||
my attention" to start from) or *Never* (runs are kept in the task's history only). Offered
|
||||
where the instance has Reports.
|
||||
- A task's runs show the run's own note -- what it found, or why it filed no report -- and a way
|
||||
to its report when it filed one. The run's working chat can still be opened from the run.
|
||||
|
||||
- **Last wake** in Settings › Wake word: when the phrase was last heard, what the app tried
|
||||
(the assistant's sheet, the sheet as a screen of the app, a notification) and exactly how it
|
||||
went -- opened, and after how long; Android had not connected LLeMbas as the assistant;
|
||||
Android refused, in its own words; or it did not refuse and still no sheet came -- with what
|
||||
Android itself said at that moment: whether LLeMbas was the digital assistant app, whether
|
||||
Android was really using it as its voice assistant, and when it had connected or dropped it.
|
||||
A tap shows the last five. Nothing from your account is in it.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The wake word heard you and only a notification came, though LLeMbas is the assistant.**
|
||||
The app can open the sheet from the background only through a connection Android keeps to
|
||||
the assistant app, and it threw away the reason when that was missing or refused. It now
|
||||
keeps it (*Last wake*), says in Settings when LLeMbas is the assistant but Android has not
|
||||
connected it right now -- with the way to the system's setting -- and checks that the sheet
|
||||
really came up before it counts the wake as opened; when it did not, the notification follows
|
||||
and says *Could not open by itself — tap to ask*. What makes a phone drop that connection is
|
||||
not fixed by this: the record is there to find out.
|
||||
- Settings says so when LLeMbas is chosen as the digital assistant app but Android is not using
|
||||
it as its voice assistant (which Android can undo at a restart): the long press then opens
|
||||
it as an ordinary screen, and the wake word can only send a notification until LLeMbas is
|
||||
chosen again.
|
||||
- The wake word stayed paused "while the assistant is open" after the sheet was left with the
|
||||
Home button, or after the assistant was asked for twice in a row.
|
||||
- A report's conversation showed the line the server opens it with as if you had written it;
|
||||
such lines are a quiet note now, and that first one is left out.
|
||||
- The screen is turned on when the wake word opens the sheet (with *Only while the screen is
|
||||
on* switched off, the phrase can come while it is dark).
|
||||
|
||||
### Changed
|
||||
|
||||
- **Notifications come from a report, not from a run**, on a *Reports* channel of their own:
|
||||
unlocked, the report's title and summary; on the lock screen only "New report". A tap opens
|
||||
the report; *Mark read* asks for the phone to be unlocked. A run that filed no report notifies
|
||||
nothing; a failed run still says that it failed. An instance on 2.0.0-beta.11 keeps sending
|
||||
its runs' notifications, and they work as before.
|
||||
- A report the model called important arrives on a channel of its own, *Important reports*,
|
||||
which may come up over what is on screen. A report read or deleted in the app takes its
|
||||
notification away. *Reports* is in the drawer only where the instance has reports. An empty
|
||||
*When…* means the instance's own default, which the field shows as a placeholder.
|
||||
- **A page in an answer is not drawn on the phone** (LLeMbas 2.0.0-beta.12 can let a model add
|
||||
HTML pages to an answer; the web and LLeMbas Desktop show them). The phone shows one quiet
|
||||
card -- *This answer has a page: …*, and where to open it -- in a chat and in a report, never
|
||||
the page's source. What you copy or share says `[page: …]` in its place. The phone's chat
|
||||
settings do not offer the switch.
|
||||
|
||||
## [1.0.0-beta.8] — 2026-11-12
|
||||
|
||||
For LLeMbas server 2.0.0-beta.11 or later. Three files now: the standard app, `-notifications` (the same app with notification summaries) and `-fdroid`.
|
||||
|
||||
### Added
|
||||
|
||||
- **Test the wake word** (Settings › Wake word): for ten seconds the row shows what the wake word
|
||||
is doing and says *Heard it* when your phrase lands, without opening the assistant -- so a
|
||||
phrase, a sensitivity and a place in the room can be tried before relying on them.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The wake word never started, on any phone.** The engine read its model out of the APK in a
|
||||
way that only works for files stored uncompressed, and they were not; the failure was swallowed,
|
||||
so the notification went on saying it listened. The model is now copied out by stream (once per
|
||||
model version, so an update that brings a new model replaces the old one) and stored
|
||||
uncompressed as well.
|
||||
- **The wake word's notification told the default phrase, not yours**, each time the app was
|
||||
opened. It is now written from one place, from what the wake word is really doing.
|
||||
- **Hearing the word when LLeMbas is not the phone's assistant and not on screen did nothing at
|
||||
all**: Android blocks an activity started from the background without saying so, and the app
|
||||
took the silence for success. It now posts *Heard you. Tap to ask.* on a channel of its own that
|
||||
comes up over what is on screen, and Settings › Wake word says plainly that only the phone's
|
||||
digital assistant app can open by voice over other apps, with a row that opens that setting.
|
||||
- The wake word could stay "paused while the assistant is open" for good if its service ended in
|
||||
the three seconds after the word. The hold now ends by itself, whatever happens to the service.
|
||||
- Turning the wake word off and on again quickly could leave "not listening" showing over a wake
|
||||
word that listened, or close the app (the service was stopped under a start still on its way).
|
||||
Stop is now the setting going off, and the service ends itself.
|
||||
- A change of phrase could release the engine while the old listening loop was still using it.
|
||||
The old loop is now stopped and waited for first.
|
||||
- A microphone that failed to start, or stopped giving sound, was not noticed (and one kind of
|
||||
failure kept a processor core busy for nothing). Both are failures that are shown now.
|
||||
- Opening the app with the wake word on but the microphone permission taken away could close the
|
||||
app. The service is no longer started without the permission; the state says what is missing.
|
||||
|
||||
### Changed
|
||||
|
||||
- **One display with the web, Desktop and the CLI** (harness spec 3.7.0, `display.md`):
|
||||
- A reply that was stopped or failed keeps the spec's line at its end -- *Stopped: by you*,
|
||||
*Stopped: step limit*, *Stopped: budget*, *Failed: …* -- an error in the error colour, a stop
|
||||
muted. A stopped reply said nothing at all before, and a failed one showed the raw error.
|
||||
- A finished tool call says how long it took (`0.4s`, `1m 05s`, `2h 03m`) where the instance
|
||||
sends the call's time; a running or a denied call shows none.
|
||||
- Counts in the progress line are in the phone's own number format (`12,480`, `12 480`,
|
||||
`12.480`); a tool call's title that had to be cut ends in `…`; the clock is joined by the
|
||||
shared separator instead of a copy of it.
|
||||
- The approval card offers the spec's four actions: *Allow once*, *Always allow*, *Deny*, and
|
||||
*Deny, and say why*. The plan card approves together with the mode to continue in --
|
||||
*Approve, continue in Edit* or *Approve, continue in Manual* -- and *Revise*.
|
||||
- With LLeMbas 2.0.0-beta.11: a reply that was stopped or failed says so with its reason after a
|
||||
reload too (the instance stores how it ended); *Always allow* is offered only where the request
|
||||
offers it; a tool call's time is the instance's own; a call without a title is named as the
|
||||
instance names its tool. The notifications build can take its own file from the instance's
|
||||
recommendation of the same release when the website's manifest names none.
|
||||
- **A reply ends when it is saved, and the chat's name follows** (with a server that sends `done`
|
||||
first: LLeMbas 2.0.0-beta.11). The app treats `done` as the end -- the transcript, a spoken
|
||||
answer and a queued prompt no longer wait for a model to name a new chat -- and takes the name
|
||||
from the `title` frame when it comes.
|
||||
- **Wake phrases the engine can hear.** "Hey Lembas" is gone: Lembas is not a word the engine's
|
||||
model was ever trained on, so it had to be repeated until it happened to land. The phrase is now
|
||||
a greeting and a name, each chosen in Settings › Wake word: **Hey**, **OK** or **Hello**, then
|
||||
**Assistant**, **Computer**, **Google** (Settings says a Google device nearby will answer too),
|
||||
or an ordinary name -- Victoria, Samantha, Jessica, Amanda, Olivia, Oliver, Sebastian, Jonathan,
|
||||
Alexander, Christopher. The default is "Hey Assistant", and a phrase saved by an earlier beta
|
||||
becomes it. The phrases are English whatever language the app is in, and Settings says so: the
|
||||
model knows English speech only.
|
||||
- **Sensitivity** (Low, Normal, High) in Settings › Wake word: how easily the phrase is taken as
|
||||
heard, against how often it starts by mistake. Each phrase now goes to the engine with a
|
||||
boosting score and a trigger threshold (1.0 / 0.35, 1.5 / 0.25, 2.0 / 0.15; a short phrase such
|
||||
as "OK Computer" is held 0.05 stricter). These are starting values from the engine's
|
||||
documentation, not yet tuned on phones.
|
||||
- The phrases' spelling in the model's token pieces is generated from the model's own tokenizer
|
||||
(`scripts/gen-wake-phrases.py`) and checked against its token table in CI, instead of written by
|
||||
hand. Elizabeth and Benjamin are left out: the tokenizer can only spell them letter by letter.
|
||||
- **Notification summaries moved to a build of their own**, `llembas-android-<version>-notifications.apk`:
|
||||
the same app with the same signature, plus the notification listener. Google Play Protect
|
||||
blocked installing beta.7, most likely because an app from outside the Play Store that can read
|
||||
notifications is what it looks for; the standard and F-Droid APKs now declare no notification
|
||||
listener at all, and Settings says where notification summaries went and why. The
|
||||
notifications build installs over the standard one as an ordinary update, and back; it updates
|
||||
itself only to its own kind.
|
||||
- **A smaller download.** Release APKs no longer carry the emulator's x86_64 libraries (about
|
||||
36 MB of beta.7's 98 MB) nor two libraries of the wake-word engine the app never calls.
|
||||
- **The wake word says what it is doing**, in its notification and under its switch in Settings:
|
||||
*Starting*, *Listening for "…"*, paused and why (screen off, battery saver, assistant open, no
|
||||
microphone permission, or the microphone gives no sound because another app has it or it is
|
||||
switched off), or not working and why (its model could not be unpacked, the engine did not
|
||||
start, the microphone did not start) -- with the technical reason under it in Settings. A
|
||||
failure is tried again by itself, after 2 s, 5 s, 15 s, a minute, then every five minutes.
|
||||
- A tap on a failure in Settings tries again at once; trouble after half a minute of listening
|
||||
well starts the waits over instead of counting on from old failures. Say the phrase and then
|
||||
leave a short pause: the engine takes it as heard once something else follows (Settings and the
|
||||
test row say so).
|
||||
- A microphone permission given or taken in the system's settings is noticed when the app comes
|
||||
back to the screen.
|
||||
|
||||
## [1.0.0-beta.7] — 2026-11-10
|
||||
|
||||
For LLeMbas server 2.0 (2.0.0-beta.10 or later for phone actions).
|
||||
|
||||
### Added
|
||||
|
||||
- **Share to LLeMbas, with a say in it.** *Ask LLeMbas* in any app's share menu now opens a
|
||||
sheet over that app: what came in (the text or link, the files by name), a line for what to do
|
||||
with it (optional), and where it goes -- a **new chat** or the **last assistant chat**. Files
|
||||
are uploaded and go with the message; the chat then opens in the app.
|
||||
- **A home-screen widget**: *Ask anything* opens the assistant, the microphone opens it
|
||||
listening, and the clock opens the last assistant chat. It shows nothing from your account.
|
||||
- **Spoken conversations with the assistant.** Ask by voice and, once the answer has been read
|
||||
aloud, the assistant listens again -- until you say "stop" (or "that's all"), tap **End**, or
|
||||
say nothing for a few seconds. The sheet says *In conversation* while it lasts. With a
|
||||
Bluetooth headset connected, its microphone is used, so the conversation can stay in your ear.
|
||||
Settings › Assistant › *Keep a spoken conversation going* (on; it needs voice replies).
|
||||
- **A wake word, if you want one** (off by default). Settings › Assistant › *Wake word*: say
|
||||
"Hey Lembas" (or one of three other English phrases) and the assistant opens, listening, over
|
||||
whatever is on screen. It listens on the phone with an open-source engine (sherpa-onnx) and a
|
||||
small on-device model; nothing leaves the phone before the word, and a notification is up the
|
||||
whole time it listens. It pauses in battery saver, while the assistant is open, and -- unless
|
||||
you change it -- with the screen off. Settings explains what it costs in battery and how to
|
||||
keep a phone's battery optimisation from stopping it. Not in the F-Droid build, which builds
|
||||
every library from source.
|
||||
- **"Summarise my notifications"**, if you allow it (off by default). Settings › Assistant ›
|
||||
*Notification summaries*, plus Android's own notification-access switch, which Settings opens
|
||||
for you. Then ask the assistant about "my notifications", or tap its chip, and the
|
||||
notifications on the phone right now go with that one question -- never before you ask, never
|
||||
while the phone is locked, and the app keeps none of them.
|
||||
- **Phone actions** (with LLeMbas server 2.0 and harness spec 3.6.0): a model may offer to do
|
||||
something on this phone -- set an alarm or a timer, add a calendar event, draft a text or an
|
||||
email, open the dialler with a number, start a route (with stops), add a stop, search nearby,
|
||||
end the route, open an app or a web page, play/pause/skip, switch the torch, open a settings
|
||||
panel, or run a Tasker task. A card says what will happen; nothing happens until you tap
|
||||
**Do it**, never while the phone is locked, and drafts and calls are left for you to send and
|
||||
place. The chat (and the assistant's sheet) tells the model whether it was done, declined or
|
||||
failed. Navigation goes to Google Maps or **OsmAnd** (Settings › Navigation app: whichever is
|
||||
installed, or ask); OsmAnd can also be asked where you are and where the running route goes,
|
||||
once you allow LLeMbas inside OsmAnd.
|
||||
- **Code in colour.** The file viewer highlights a source file by its language (as the server
|
||||
names it), and a reply's code blocks by their fence's language: comments, strings, numbers,
|
||||
keywords, type names, and markup's tags and attributes, in the theme's own colours in Shire
|
||||
and Moria. Still read-only; a language it does not know is shown plain.
|
||||
- **Launcher shortcuts** (long-press the icon): Ask LLeMbas, Speak, Last chat.
|
||||
- **A headset's voice button** opens the assistant listening, when LLeMbas answers it; over the
|
||||
lock screen it asks to unlock first.
|
||||
|
||||
### Changed
|
||||
|
||||
- The Quick Settings tile always shows as ready, never greyed out.
|
||||
|
||||
## [1.0.0-beta.6] — 2026-11-10
|
||||
|
||||
For LLeMbas server 2.0 (2.0.0-beta.9 or later for schedules on a computer, the update check through the instance, pinning, folders, memory and search).
|
||||
|
||||
@@ -40,13 +40,34 @@ certificate). The app trusts CAs you installed, as the browser does.
|
||||
digital assistant app. On Samsung phones also set Settings › Advanced features › Side button ›
|
||||
Press and hold › Digital assistant.
|
||||
|
||||
There is no wake word. Android reserves always-on hotword detection for the system's own
|
||||
preinstalled assistant; no app from outside can use it.
|
||||
A wake word is there if you want one, off by default: Settings › Assistant › Wake word, a
|
||||
greeting and a name in English ("Hey Assistant"). Android reserves its low-power, always-on
|
||||
hotword detection for the system's own preinstalled assistant, so LLeMbas listens with an
|
||||
on-device engine in a microphone service, with a notification up the whole time; nothing leaves
|
||||
the phone before the word. Not in the F-Droid build.
|
||||
|
||||
The wake word and the hands-free parts of the voice assistant (listening by itself, the spoken
|
||||
conversation) are **experimental**: new, and tried on few phones. Settings marks them so.
|
||||
|
||||
Over the lock screen the assistant can listen (the wake word, a headset's button), but nothing
|
||||
goes to the instance and no answer is shown or spoken until the phone is unlocked: with the
|
||||
instance's speech-to-text the question waits on the phone as a recording.
|
||||
|
||||
## Build
|
||||
|
||||
Builds run on GitHub Actions (`.github/workflows/ci.yml`); locally it is the usual
|
||||
`./gradlew assembleFullDebug` with JDK 17 and the Android SDK.
|
||||
Builds run on GitHub Actions (`.github/workflows/ci.yml`); locally it is
|
||||
`scripts/fetch-wakeword.py` (the wake-word engine and model, hash-pinned, never committed) and
|
||||
then the usual `./gradlew assembleFullStandardDebug` with JDK 17 and the Android SDK.
|
||||
|
||||
A release is three APKs of one app, signed with one key:
|
||||
|
||||
| File | Build | What it is |
|
||||
|---|---|---|
|
||||
| `llembas-android-<version>.apk` | `fullStandard` | The app: updates itself, has the wake word. The one to install. |
|
||||
| `llembas-android-<version>-notifications.apk` | `fullNotifications` | The same, plus a notification listener for *notification summaries*. Separate because Google Play Protect blocks installing an app from outside the Play Store that can read notifications; it installs over the standard one, and back. |
|
||||
| `llembas-android-<version>-fdroid.apk` | `fdroidStandard` | No updater and no wake-word engine: only what F-Droid can build from source. |
|
||||
|
||||
`scripts/check-apk.sh` checks each built file for what it must and must not declare.
|
||||
|
||||
Three things are generated from the server at one ref; the first two are pinned with a lock
|
||||
file CI checks, and CI checks the strings against the code:
|
||||
|
||||
+49
-3
@@ -31,7 +31,7 @@ android {
|
||||
// The one source of the version. versionCode is derived from it, so the two cannot
|
||||
// drift, and a beta sorts below its release: 1.0.0-beta.1 -> 1000001,
|
||||
// 1.0.0-beta.2 -> 1000002, 1.0.0 -> 1000099, 1.2.3 -> 1020399.
|
||||
versionName = "1.0.0-beta.6"
|
||||
versionName = "1.0.0-beta.15"
|
||||
versionCode = versionName!!.split("-beta.").let { parts ->
|
||||
val (a, b, c) = parts[0].split(".").map { it.toInt() }
|
||||
val pre = if (parts.size == 2) parts[1].toInt() else 99
|
||||
@@ -67,17 +67,31 @@ android {
|
||||
isShrinkResources = true
|
||||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||
signingConfig = signingConfigs.findByName("release")
|
||||
// The wake-word engine's native code, for phones only: a release carries no x86_64
|
||||
// library (36 MB that only an emulator would load).
|
||||
ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a") }
|
||||
}
|
||||
debug {
|
||||
applicationIdSuffix = ".debug"
|
||||
// CI's run number, so a tester can tell two test builds apart in Settings › About.
|
||||
versionNameSuffix = "-debug" + (System.getenv("GITHUB_RUN_NUMBER")?.let { ".$it" } ?: "")
|
||||
signingConfig = signingConfigs.getByName("debug")
|
||||
// A test build also runs on the 64-bit emulator (not 32-bit x86).
|
||||
ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a", "x86_64") }
|
||||
}
|
||||
}
|
||||
|
||||
// `full` updates itself from llembas.eu; `fdroid` has no updater, because F-Droid updates it.
|
||||
flavorDimensions += "distribution"
|
||||
// Two questions, three APKs.
|
||||
//
|
||||
// `distribution`: `full` updates itself from llembas.eu and has the wake-word engine; `fdroid`
|
||||
// has neither, because F-Droid updates it and builds every library from source.
|
||||
//
|
||||
// `reading`: whether the app declares a notification listener (notification summaries).
|
||||
// `standard` does not -- no listener, no permission, nothing of it in the manifest -- because
|
||||
// Google Play Protect blocks installing an app from outside the Play Store that can read
|
||||
// notifications. `notifications` is the full build plus the listener: the same application
|
||||
// id and the same key, so it installs over the standard one as an ordinary update.
|
||||
flavorDimensions += listOf("distribution", "reading")
|
||||
productFlavors {
|
||||
create("full") {
|
||||
dimension = "distribution"
|
||||
@@ -87,6 +101,26 @@ android {
|
||||
dimension = "distribution"
|
||||
buildConfigField("boolean", "SELF_UPDATE", "false")
|
||||
}
|
||||
create("standard") {
|
||||
dimension = "reading"
|
||||
}
|
||||
create("notifications") {
|
||||
dimension = "reading"
|
||||
}
|
||||
}
|
||||
|
||||
androidResources {
|
||||
// The wake-word model is read as files the engine opens itself: stored as it is, never
|
||||
// deflated a second time (it does not shrink, and nothing has to inflate it on the phone).
|
||||
noCompress += "onnx"
|
||||
}
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
// The engine is called through its JNI library alone, which needs only onnxruntime;
|
||||
// the C and C++ API libraries its AAR also carries are for other kinds of caller.
|
||||
excludes += listOf("**/libsherpa-onnx-c-api.so", "**/libsherpa-onnx-cxx-api.so")
|
||||
}
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
@@ -130,6 +164,14 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
// fullStandard, fullNotifications and fdroidStandard: there is no F-Droid build with the listener.
|
||||
androidComponents {
|
||||
beforeVariants { variant ->
|
||||
val flavors = variant.productFlavors.toMap()
|
||||
if (flavors["distribution"] == "fdroid" && flavors["reading"] == "notifications") variant.enable = false
|
||||
}
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
}
|
||||
@@ -156,6 +198,10 @@ dependencies {
|
||||
implementation(libs.markwon.tables)
|
||||
implementation(libs.markwon.strikethrough)
|
||||
implementation(libs.unifiedpush.connector)
|
||||
// The wake-word engine, sherpa-onnx (Apache-2.0), in the `full` build only: its prebuilt Android
|
||||
// library, fetched hash-pinned by scripts/fetch-wakeword.py (never committed). The `fdroid`
|
||||
// build, which F-Droid builds from source, has no engine (src/fdroid/.../wake/Engine.kt).
|
||||
add("fullImplementation", files("libs/sherpa-onnx-2.0.1.aar"))
|
||||
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.kotlinx.coroutines.test)
|
||||
|
||||
Vendored
+3
@@ -17,3 +17,6 @@
|
||||
-dontwarn org.conscrypt.**
|
||||
-dontwarn org.bouncycastle.**
|
||||
-dontwarn org.openjsse.**
|
||||
|
||||
# The wake-word engine's JNI reads its config classes' fields by name.
|
||||
-keep class com.k2fsa.sherpa.onnx.** { *; }
|
||||
@@ -0,0 +1,14 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import android.content.Context
|
||||
|
||||
/**
|
||||
* The F-Droid build has no wake-word engine: F-Droid builds every library from source, and the
|
||||
* engine (sherpa-onnx, Apache-2.0) comes to the other build as its project's prebuilt Android
|
||||
* library. Settings says so; everything else about the wake word is the same code in both.
|
||||
*/
|
||||
object WakeEngine {
|
||||
const val AVAILABLE = false
|
||||
|
||||
fun create(context: Context, keywords: String): WakeDetector = throw WakeError(WakeFailure.NoEngine, message = "this build has no wake-word engine")
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import android.content.Context
|
||||
import com.k2fsa.sherpa.onnx.FeatureConfig
|
||||
import com.k2fsa.sherpa.onnx.KeywordSpotter
|
||||
import com.k2fsa.sherpa.onnx.KeywordSpotterConfig
|
||||
import com.k2fsa.sherpa.onnx.OnlineModelConfig
|
||||
import com.k2fsa.sherpa.onnx.OnlineStream
|
||||
import com.k2fsa.sherpa.onnx.OnlineTransducerModelConfig
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The wake-word engine: sherpa-onnx's keyword spotter (Apache-2.0) with its small English model
|
||||
* (a 3.3M-parameter zipformer, int8, Apache-2.0), both fetched hash-pinned at build time by
|
||||
* `scripts/fetch-wakeword.py`. It runs on the phone's CPU, one thread, on the 16 kHz samples the
|
||||
* service hands it; nothing leaves the phone.
|
||||
*
|
||||
* The model's files are copied out of the APK's assets into the app's no-backup files
|
||||
* ([unpackWakeModel]: by stream, keyed by the model's version), so the engine reads them as files
|
||||
* beside a keywords file written for the chosen phrase.
|
||||
*/
|
||||
object WakeEngine {
|
||||
const val AVAILABLE = true
|
||||
|
||||
private val FILES = listOf("encoder.int8.onnx", "decoder.int8.onnx", "joiner.int8.onnx", "tokens.txt")
|
||||
|
||||
/**
|
||||
* The engine for [keywords] (the keywords file's text). Throws a [WakeError] that says which
|
||||
* half failed -- the model's files or the engine -- and never returns nothing.
|
||||
*
|
||||
* One at a time: two service instances may overlap for a moment (the wake word turned off and
|
||||
* on again), and the unpacking and the keywords file are shared. The keywords go into a file
|
||||
* of this call's own, which the engine reads as it is made and which is gone afterwards.
|
||||
*/
|
||||
@Synchronized
|
||||
fun create(context: Context, keywords: String): WakeDetector {
|
||||
val dir = File(context.noBackupFilesDir, "wakeword")
|
||||
try {
|
||||
unpackWakeModel({ context.assets.open("wakeword/$it") }, dir, FILES)
|
||||
} catch (e: Exception) {
|
||||
throw WakeError(WakeFailure.Model, e)
|
||||
}
|
||||
checkKeywords(keywords, File(dir, "tokens.txt").readText())
|
||||
var file: File? = null
|
||||
try {
|
||||
val written = File.createTempFile("keywords", ".txt", dir)
|
||||
file = written
|
||||
written.writeText(keywords)
|
||||
val config = KeywordSpotterConfig(
|
||||
featConfig = FeatureConfig(sampleRate = RATE, featureDim = 80),
|
||||
modelConfig = OnlineModelConfig(
|
||||
transducer = OnlineTransducerModelConfig(
|
||||
encoder = File(dir, "encoder.int8.onnx").path,
|
||||
decoder = File(dir, "decoder.int8.onnx").path,
|
||||
joiner = File(dir, "joiner.int8.onnx").path,
|
||||
),
|
||||
tokens = File(dir, "tokens.txt").path,
|
||||
modelType = "zipformer2",
|
||||
numThreads = 1,
|
||||
),
|
||||
keywordsFile = written.path,
|
||||
// The engine's own default (the Kotlin wrapper's is 2). The phrase counts once
|
||||
// MORE than this many blank frames follow it -- two frames, about 80 ms of
|
||||
// anything that is not the phrase going on. So: say it, then a short pause; a
|
||||
// question run straight into the name can be missed.
|
||||
numTrailingBlanks = 1,
|
||||
)
|
||||
return SherpaDetector(KeywordSpotter(null, config))
|
||||
} catch (e: Throwable) {
|
||||
// UnsatisfiedLinkError included: a phone whose processor the library was not built for.
|
||||
throw WakeError(WakeFailure.Engine, e)
|
||||
} finally {
|
||||
file?.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private const val RATE = 16_000
|
||||
|
||||
private class SherpaDetector(private val spotter: KeywordSpotter) : WakeDetector {
|
||||
private val stream: OnlineStream = spotter.createStream()
|
||||
|
||||
override fun accept(samples: FloatArray): Boolean {
|
||||
stream.acceptWaveform(samples, RATE)
|
||||
while (spotter.isReady(stream)) {
|
||||
spotter.decode(stream)
|
||||
if (spotter.getResult(stream).keyword.isNotBlank()) {
|
||||
spotter.reset(stream)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
override fun release() {
|
||||
stream.release()
|
||||
spotter.release()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,17 @@
|
||||
<!-- Dictation and the assistant's voice. Asked for the first time either is used. -->
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- A spoken conversation through a Bluetooth headset: its microphone made the route. -->
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
<!-- The wake word (opt-in): a microphone foreground service, and "tap to listen again"
|
||||
after a restart. -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<!-- Phone actions: an alarm or a timer, set through the clock app once the person confirms. -->
|
||||
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
|
||||
<!-- Phone actions: run a Tasker task by its name (Tasker asks the person to allow it). -->
|
||||
<uses-permission android:name="net.dinglisch.android.tasker.PERMISSION_RUN_TASKS" />
|
||||
|
||||
<queries>
|
||||
<!-- UnifiedPush distributors (ntfy and others) are found by this action. -->
|
||||
@@ -15,6 +26,16 @@
|
||||
<intent>
|
||||
<action android:name="android.speech.RecognitionService" />
|
||||
</intent>
|
||||
<!-- Phone actions: "open an app" by its name, and the navigation apps a route goes to. -->
|
||||
<intent>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent>
|
||||
<package android:name="com.google.android.apps.maps" />
|
||||
<package android:name="net.osmand.plus" />
|
||||
<package android:name="net.osmand" />
|
||||
<package android:name="net.osmand.dev" />
|
||||
<package android:name="net.dinglisch.android.taskerm" />
|
||||
</queries>
|
||||
|
||||
<application
|
||||
@@ -38,14 +59,18 @@
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.app.shortcuts" android:resource="@xml/shortcuts" />
|
||||
</activity>
|
||||
|
||||
<!-- The assistant's sheet as an activity: the tile, the shortcut, ACTION_ASSIST, and
|
||||
the lock-screen path (it asks to unlock before sending anything). -->
|
||||
<!-- The assistant's sheet as an activity: the tile, the widget, the shortcuts,
|
||||
ACTION_ASSIST, a headset's voice button, and the lock-screen path (it asks to
|
||||
unlock before sending anything). Exported for Android's own actions; what only the
|
||||
app's own parts may ask of it is told apart in OwnIntents.kt. It handles
|
||||
configuration changes itself (Compose redraws): turned, folded or switched to the
|
||||
dark theme, it is not made again, and neither is the question it holds. -->
|
||||
<activity
|
||||
android:name=".assist.AssistActivity"
|
||||
android:exported="true"
|
||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden|navigation|uiMode|density|fontScale"
|
||||
android:excludeFromRecents="true"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity=""
|
||||
@@ -55,6 +80,15 @@
|
||||
<action android:name="android.intent.action.ASSIST" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
<!-- A headset's voice button: the sheet opens listening. -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VOICE_COMMAND" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.speech.action.VOICE_SEARCH_HANDS_FREE" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -62,7 +96,9 @@
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:label="@string/share_label"
|
||||
android:taskAffinity="">
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/Theme.Lembas.Sheet"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
@@ -78,6 +114,25 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- Phone actions: asks another app for a result (OsmAnd's get_info) and goes. -->
|
||||
<activity
|
||||
android:name=".actions.ActionRunner$ResultActivity"
|
||||
android:excludeFromRecents="true"
|
||||
android:exported="false"
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/Theme.Lembas.Sheet" />
|
||||
|
||||
<!-- The home-screen widget: Ask, the microphone, the last assistant chat. -->
|
||||
<receiver
|
||||
android:name=".widget.AskWidget"
|
||||
android:exported="true"
|
||||
android:label="@string/tile_ask">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_ask" />
|
||||
</receiver>
|
||||
|
||||
<!-- The digital assistant: Settings › Default apps › Digital assistant app. -->
|
||||
<service
|
||||
android:name=".assist.LembasAssistService"
|
||||
@@ -112,6 +167,8 @@
|
||||
android:icon="@drawable/ic_notification"
|
||||
android:label="@string/tile_ask"
|
||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
|
||||
<!-- A button, not a switch. -->
|
||||
<meta-data android:name="android.service.quicksettings.TOGGLEABLE_TILE" android:value="false" />
|
||||
<intent-filter>
|
||||
<action android:name="android.service.quicksettings.action.QS_TILE" />
|
||||
</intent-filter>
|
||||
@@ -125,16 +182,38 @@
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<!-- The wake word: listens only while its notification is up (wake/WakeWordService.kt). -->
|
||||
<service
|
||||
android:name=".wake.WakeWordService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="microphone" />
|
||||
|
||||
<receiver
|
||||
android:name=".wake.WakeBootReceiver"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<receiver
|
||||
android:name=".push.CardActionReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<!-- A report's Mark read, from its notification. -->
|
||||
<receiver
|
||||
android:name=".push.ReportActionReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<!-- A scheduled task's Pause, from its notification. -->
|
||||
<receiver
|
||||
android:name=".push.ScheduleActionReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<!-- A photo for the composer: the camera app writes into one file in the cache. -->
|
||||
<!-- One file of the private cache at a time, to one other app: the photo the camera app
|
||||
takes for the composer, and the copy of a file that Open with or Share hands over
|
||||
(res/xml/file_paths.xml names the two folders). Not exported. -->
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.files"
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* Whether a new request that carries the account's files may start: only while the app is in
|
||||
* front and the phone is unlocked. Work that goes on by itself -- a queue of uploads, the copies
|
||||
* for a share, a player's copy -- asks [pass] before each request. A request already on its way
|
||||
* is not touched, so what the person started finishes; the next one waits here, and goes on by
|
||||
* itself when the app is in front of an unlocked phone again.
|
||||
*
|
||||
* The process has one ([LembasApp.gate]). It hears of the app's activities starting and stopping,
|
||||
* of the assistant's sheet showing and hiding (a session's window, which is no activity), and of
|
||||
* the screen going off and the phone being unlocked; [locked] is asked each time.
|
||||
*/
|
||||
class InstanceGate(private val locked: () -> Boolean) {
|
||||
private val started = AtomicInteger(0)
|
||||
private val sheet = AtomicBoolean(false)
|
||||
private val state = MutableStateFlow(false)
|
||||
|
||||
/** Whether a request may start now, as it was last looked at. */
|
||||
val open: StateFlow<Boolean> = state.asStateFlow()
|
||||
|
||||
fun activityStarted() {
|
||||
started.incrementAndGet()
|
||||
look()
|
||||
}
|
||||
|
||||
fun activityStopped() {
|
||||
started.updateAndGet { (it - 1).coerceAtLeast(0) }
|
||||
look()
|
||||
}
|
||||
|
||||
/**
|
||||
* The assistant's sheet is up. It is a window of the system's session and no activity, so it
|
||||
* says so itself: the app is in front while it shows, as while an activity is started. Told
|
||||
* once however often the system shows a sheet that is already up. The lock still shuts the
|
||||
* gate: a sheet over the lock screen asks the instance for nothing.
|
||||
*/
|
||||
fun sessionShown() {
|
||||
sheet.set(true)
|
||||
look()
|
||||
}
|
||||
|
||||
fun sessionHidden() {
|
||||
sheet.set(false)
|
||||
look()
|
||||
}
|
||||
|
||||
/** Looks again (the screen went off, the phone was unlocked) and says whether a request may start. */
|
||||
fun look(): Boolean {
|
||||
val now = (started.get() > 0 || sheet.get()) && !locked()
|
||||
state.value = now
|
||||
return now
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns when a request may start. [waiting] hears `true` when that is not now, and `false`
|
||||
* when the wait is over (also when it is given up), so a screen can say what it is waiting
|
||||
* for. While waiting the lock is looked at again every [AGAIN_MS]: an unlock nobody
|
||||
* announced must not leave a queue standing.
|
||||
*/
|
||||
suspend fun pass(waiting: (Boolean) -> Unit = {}) {
|
||||
if (look()) return
|
||||
waiting(true)
|
||||
try {
|
||||
while (!look()) withTimeoutOrNull(AGAIN_MS) { state.first { it } }
|
||||
} finally {
|
||||
waiting(false)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [pass], for a wait that may last as long as the phone lies locked or the app is away: it
|
||||
* sleeps until the gate is told of a change (an activity starting, the unlock) instead of
|
||||
* looking at the lock every second, and only then takes its turn as [pass] does.
|
||||
*/
|
||||
suspend fun passLater() {
|
||||
if (!look()) state.first { it }
|
||||
pass()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val AGAIN_MS = 1_000L
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [work], for as long as a request may start: something nobody asked for (a reply that began by
|
||||
* itself) is followed only while the app is in front of an unlocked phone. When the gate closes
|
||||
* the work is let go -- cancelled, with its connection -- and the answer is null; so it is when
|
||||
* the gate is closed already, and then nothing is started. [stays] says the work is the
|
||||
* person's own after all (they asked for it while it ran): that goes on behind the gate, as a
|
||||
* request under way does. The caller's own cancellation is not taken for a letting go.
|
||||
*/
|
||||
suspend fun <T : Any> InstanceGate.whileOpen(stays: () -> Boolean = { false }, work: suspend () -> T): T? {
|
||||
if (!look() && !stays()) return null
|
||||
return coroutineScope {
|
||||
val doing = async { work() }
|
||||
val watch = launch {
|
||||
open.first { !it && !stays() }
|
||||
doing.cancel()
|
||||
}
|
||||
try {
|
||||
doing.await()
|
||||
} catch (e: CancellationException) {
|
||||
// The caller's own end is the caller's; only the gate's is "let go".
|
||||
currentCoroutineContext().ensureActive()
|
||||
null
|
||||
} finally {
|
||||
watch.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [send] for each of [items] from the one at [from], each after its [turn] at the gate, and
|
||||
* [done] hears how many are through after each. A failure leaves the count where it was, so
|
||||
* the same call with that count takes the queue up at the one that failed, not at the first.
|
||||
*/
|
||||
suspend fun <T> sendFrom(items: List<T>, from: Int, turn: suspend () -> Unit, done: (Int) -> Unit, send: suspend (T) -> Unit) {
|
||||
for (i in from.coerceAtLeast(0) until items.size) {
|
||||
turn()
|
||||
send(items[i])
|
||||
done(i + 1)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The assistant's sheet as the gate hears of it: every way the session's window can go says so.
|
||||
* Android may show a sheet that is up again, hide it once, or tear the session down without
|
||||
* hiding it at all -- [gone] is for each of those ends, so the sheet can never be left counted
|
||||
* as the app in front when nothing of the app is.
|
||||
*/
|
||||
class SheetAtGate(private val gate: InstanceGate) {
|
||||
fun shown() = gate.sessionShown()
|
||||
|
||||
/** Hidden, destroyed, or its service gone: whichever comes, and however many of them. */
|
||||
fun gone() = gate.sessionHidden()
|
||||
}
|
||||
@@ -1,18 +1,98 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Application
|
||||
import android.app.KeyguardManager
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.Bundle
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.api.EventsHub
|
||||
import eu.llembas.android.api.Frame
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.auth.InstanceStore
|
||||
import eu.llembas.android.wake.AppVisibility
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/** The process: one store of instances, and the notification channels, made once. */
|
||||
class LembasApp : Application() {
|
||||
lateinit var instances: InstanceStore
|
||||
private set
|
||||
|
||||
/** The one connection to the person's events route, shared by all that watch it. */
|
||||
val events = EventsHub(CoroutineScope(SupervisorJob() + Dispatchers.Default))
|
||||
|
||||
/**
|
||||
* The events route of the instance in use, as its frames; null when not signed in. Whoever
|
||||
* collects them does so only while its screen is in front (`repeatOnLifecycle`), never from
|
||||
* a scope that outlives the screen: the connection is open for as long as anybody listens.
|
||||
*/
|
||||
suspend fun eventFrames(): Flow<Frame>? {
|
||||
val instance = instances.current() ?: return null
|
||||
val api = instances.clientFor(instance)
|
||||
// Every opening of the route waits at the gate: it is not opened, or opened again, behind a lock.
|
||||
return events.frames(instance.id) { StreamClient(api).watch(turn = { gate.pass() }) { api.events() } }
|
||||
}
|
||||
|
||||
/** Whether a new request with the account's files may start: the app in front, the phone unlocked. */
|
||||
val gate = InstanceGate { getSystemService(KeyguardManager::class.java)?.isKeyguardLocked == true }
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instances = InstanceStore(this)
|
||||
// Copies of the account's files left by a process that was killed. A viewer's own are
|
||||
// nobody's now; one another app was handed may still be read there (a mail being
|
||||
// written), so those go by their age only.
|
||||
eu.llembas.android.ui.files.FileCache.atStart(this)
|
||||
// The gate hears the lock from the screen going off and the unlock; the activities below say the rest.
|
||||
ContextCompat.registerReceiver(
|
||||
this,
|
||||
object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
gate.look()
|
||||
}
|
||||
},
|
||||
IntentFilter().apply {
|
||||
addAction(Intent.ACTION_USER_PRESENT)
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
addAction(Intent.ACTION_SCREEN_ON)
|
||||
},
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
// Whether the app is on screen: the wake word may open the assistant's sheet as an
|
||||
// activity only then (Android blocks one started from the background, silently).
|
||||
registerActivityLifecycleCallbacks(
|
||||
object : ActivityLifecycleCallbacks {
|
||||
override fun onActivityStarted(activity: Activity) {
|
||||
AppVisibility.activityStarted()
|
||||
gate.activityStarted()
|
||||
}
|
||||
|
||||
override fun onActivityStopped(activity: Activity) {
|
||||
AppVisibility.activityStopped()
|
||||
gate.activityStopped()
|
||||
}
|
||||
|
||||
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
|
||||
|
||||
override fun onActivityResumed(activity: Activity) {
|
||||
gate.look()
|
||||
}
|
||||
|
||||
override fun onActivityPaused(activity: Activity) = Unit
|
||||
|
||||
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
|
||||
|
||||
override fun onActivityDestroyed(activity: Activity) = Unit
|
||||
},
|
||||
)
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannels(
|
||||
listOf(
|
||||
@@ -20,13 +100,18 @@ class LembasApp : Application() {
|
||||
NotificationChannel(CHANNEL_ASKS, getString(R.string.channel_asks), NotificationManager.IMPORTANCE_HIGH),
|
||||
NotificationChannel(CHANNEL_SCHEDULED, getString(R.string.channel_scheduled), NotificationManager.IMPORTANCE_DEFAULT),
|
||||
NotificationChannel(CHANNEL_SCHEDULED_FAILURES, getString(R.string.channel_scheduled_failures), NotificationManager.IMPORTANCE_HIGH),
|
||||
NotificationChannel(CHANNEL_REPORTS, getString(R.string.channel_reports), NotificationManager.IMPORTANCE_DEFAULT),
|
||||
NotificationChannel(CHANNEL_REPORTS_HIGH, getString(R.string.channel_reports_high), NotificationManager.IMPORTANCE_HIGH),
|
||||
).onEach { it.lockscreenVisibility = android.app.Notification.VISIBILITY_PRIVATE } +
|
||||
// A new version of the app says nothing about the account.
|
||||
NotificationChannel(CHANNEL_UPDATES, getString(R.string.channel_updates), NotificationManager.IMPORTANCE_LOW),
|
||||
)
|
||||
// LLeMbas 2.0 has no reports, so 0.1's channel for them goes rather than sit empty in
|
||||
// the system's settings.
|
||||
// 0.1's channel for its reports goes rather than sit empty in the system's settings;
|
||||
// the reports of LLeMbas 2.0 have a channel of their own (CHANNEL_REPORTS).
|
||||
manager.deleteNotificationChannel("reports")
|
||||
// The launcher's long-press shortcuts, in the app's language as it is now.
|
||||
eu.llembas.android.widget.Shortcuts.publish(this)
|
||||
eu.llembas.android.widget.AskWidget.refresh(this)
|
||||
}
|
||||
|
||||
companion object {
|
||||
@@ -34,6 +119,8 @@ class LembasApp : Application() {
|
||||
const val CHANNEL_ASKS = "asks"
|
||||
const val CHANNEL_SCHEDULED = "scheduled_results"
|
||||
const val CHANNEL_SCHEDULED_FAILURES = "scheduled_failures"
|
||||
const val CHANNEL_REPORTS = "reports_filed"
|
||||
const val CHANNEL_REPORTS_HIGH = "reports_important"
|
||||
const val CHANNEL_UPDATES = "updates"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
@@ -20,13 +21,17 @@ import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
@@ -34,6 +39,7 @@ import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.Folder
|
||||
import eu.llembas.android.api.safeId
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.push.Notifications
|
||||
@@ -45,15 +51,21 @@ import eu.llembas.android.ui.home.ChatsViewModel
|
||||
import eu.llembas.android.ui.home.DrawerActions
|
||||
import eu.llembas.android.ui.home.DrawerContent
|
||||
import eu.llembas.android.ui.memory.MemoryScreen
|
||||
import eu.llembas.android.ui.reports.ReportScreen
|
||||
import eu.llembas.android.ui.reports.ReportsScreen
|
||||
import eu.llembas.android.ui.scheduled.RunScreen
|
||||
import eu.llembas.android.ui.scheduled.ScheduleEditScreen
|
||||
import eu.llembas.android.ui.scheduled.ScheduleScreen
|
||||
import eu.llembas.android.ui.scheduled.ScheduledScreen
|
||||
import eu.llembas.android.ui.scheduled.SchedulingModelsScreen
|
||||
import eu.llembas.android.ui.settings.McpScreen
|
||||
import eu.llembas.android.ui.settings.SettingsScreen
|
||||
import eu.llembas.android.ui.signin.SignInScreen
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.update.ReleaseCheck
|
||||
import eu.llembas.android.wake.WakeBootReceiver
|
||||
import eu.llembas.android.wake.WakeEngine
|
||||
import eu.llembas.android.wake.WakeWordService
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
@@ -62,7 +74,7 @@ import kotlinx.coroutines.launch
|
||||
private data class Loaded(val instance: Instance?)
|
||||
|
||||
/** Where a notification (or the assistant, or a share) asked the app to open. */
|
||||
private data class Opening(val chat: String?, val schedule: String?, val run: String? = null, val instance: String? = null)
|
||||
private data class Opening(val chat: String?, val schedule: String?, val run: String? = null, val instance: String? = null, val report: String? = null)
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
/** A chat or a schedule a notification, the assistant or a share asked to open; consumed once. */
|
||||
@@ -90,6 +102,18 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A wake word that is on, but whose service the phone stopped, listens again -- each time the
|
||||
* app comes to the screen, which is also when a microphone permission given or taken in the
|
||||
* system's settings is noticed ([WakeWordService.start] says which it is).
|
||||
*/
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
lifecycleScope.launch {
|
||||
if (WakeEngine.AVAILABLE && lembas.instances.prefs.first().wakeWord) WakeWordService.start(this@MainActivity)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the app in the language Settings › Language says: the account's by default. A
|
||||
* language chosen for the app in the system's own settings (Android 13+) since the app last
|
||||
@@ -115,12 +139,20 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun take(intent: Intent?) {
|
||||
val chat = intent?.getStringExtra(Notifications.EXTRA_CHAT)
|
||||
val schedule = intent?.getStringExtra(Notifications.EXTRA_SCHEDULE)
|
||||
val run = intent?.getStringExtra(Notifications.EXTRA_RUN)
|
||||
// "Tap to listen again" after a restart: the app is on screen now, so the microphone
|
||||
// service may start.
|
||||
if (intent?.getBooleanExtra(WakeBootReceiver.EXTRA_RESUME, false) == true) {
|
||||
lifecycleScope.launch { if (lembas.instances.prefs.first().wakeWord) WakeWordService.start(this@MainActivity) }
|
||||
}
|
||||
// Extras are whatever the sender put there (this activity can be started from outside):
|
||||
// only ids that look like ids go on to become routes.
|
||||
val chat = safeId(intent?.getStringExtra(Notifications.EXTRA_CHAT))
|
||||
val schedule = safeId(intent?.getStringExtra(Notifications.EXTRA_SCHEDULE))
|
||||
val run = safeId(intent?.getStringExtra(Notifications.EXTRA_RUN))
|
||||
val instance = intent?.getStringExtra(Notifications.EXTRA_INSTANCE)
|
||||
if (chat == null && schedule == null) return
|
||||
opening.value = Opening(chat, schedule, run, instance)
|
||||
val report = safeId(intent?.getStringExtra(Notifications.EXTRA_REPORT))
|
||||
if (chat == null && schedule == null && report == null) return
|
||||
opening.value = Opening(chat, schedule, run, instance, report)
|
||||
// A notification from another of the person's instances: that one comes into use, and
|
||||
// its pages (keyed by the instance) open what was asked.
|
||||
if (instance != null) {
|
||||
@@ -180,7 +212,19 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
// The list is read again each time the drawer opens, so a new title or a finished
|
||||
// reply's dot is there without a pull.
|
||||
LaunchedEffect(drawer.isOpen) { if (drawer.isOpen) chats.load() }
|
||||
// While it is open the list follows the replies; closed, nothing reads it.
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
LaunchedEffect(drawer.isOpen) {
|
||||
chats.shown(drawer.isOpen)
|
||||
if (drawer.isOpen) {
|
||||
chats.load()
|
||||
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { chats.watchRunning() }
|
||||
}
|
||||
}
|
||||
// The chat on screen: the end of its reply is not something new in the list.
|
||||
LaunchedEffect(current) { chats.open = current }
|
||||
// The badge on Reports follows the instance while the app is in front.
|
||||
LaunchedEffect(instance.id) { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { chats.watchReports() } }
|
||||
LaunchedEffect(open) {
|
||||
open?.let {
|
||||
// Meant for another instance: left for that one's pages, once it is in use.
|
||||
@@ -188,6 +232,8 @@ class MainActivity : ComponentActivity() {
|
||||
when {
|
||||
it.chat != null -> top("chat/${it.chat}")
|
||||
|
||||
it.report != null -> over("report/${it.report}")
|
||||
|
||||
it.schedule != null -> {
|
||||
over("schedule/${it.schedule}")
|
||||
it.run?.let { run -> over("schedule/${it.schedule}/run/$run") }
|
||||
@@ -222,6 +268,8 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun scheduled() = over("scheduled")
|
||||
|
||||
override fun reports() = over("reports")
|
||||
|
||||
override fun archived() = over("archived")
|
||||
|
||||
override fun memory() = over("memory")
|
||||
@@ -235,7 +283,10 @@ class MainActivity : ComponentActivity() {
|
||||
override fun search(query: String) = chats.search(query)
|
||||
}
|
||||
}
|
||||
// The title of each report whose conversation was opened, by its chat: what that chat's bar says.
|
||||
val reportTitles = remember { mutableStateMapOf<String, String>() }
|
||||
val menu: () -> Unit = { scope.launch { drawer.open() } }
|
||||
val filesAt: (String) -> Unit = { folder -> over("files-at/" + Uri.encode(folder)) }
|
||||
ModalNavigationDrawer(
|
||||
drawerState = drawer,
|
||||
// The drawer opens by a swipe only from a chat: elsewhere the swipe is Back's.
|
||||
@@ -253,6 +304,7 @@ class MainActivity : ComponentActivity() {
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { top("new") },
|
||||
onOpened = { id -> top("chat/$id") },
|
||||
onFiles = filesAt,
|
||||
)
|
||||
}
|
||||
composable("new-agent") {
|
||||
@@ -272,13 +324,42 @@ class MainActivity : ComponentActivity() {
|
||||
onMenu = menu,
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { top("new") },
|
||||
onFiles = filesAt,
|
||||
)
|
||||
}
|
||||
composable("files") { FilesScreen(onBack = { nav.popBackStack() }) }
|
||||
// Files at a folder: where a generated file's "Open in Files" leads.
|
||||
composable("files-at/{at}") { e -> FilesScreen(onBack = { nav.popBackStack() }, start = e.arguments?.getString("at")) }
|
||||
composable("mcp") { McpScreen(onBack = { nav.popBackStack() }) }
|
||||
composable("archived") {
|
||||
ArchivedScreen(onBack = { nav.popBackStack() }, onOpen = { top("chat/$it") }, onRestored = { chats.load() })
|
||||
}
|
||||
composable("memory") { MemoryScreen(onBack = { nav.popBackStack() }) }
|
||||
composable("reports") { ReportsScreen(onBack = { nav.popBackStack() }, onOpen = { over("report/$it") }) }
|
||||
composable("report/{id}") { e ->
|
||||
ReportScreen(
|
||||
e.arguments?.getString("id").orEmpty(),
|
||||
onBack = { nav.popBackStack() },
|
||||
onReply = { chat, title ->
|
||||
reportTitles[chat] = title
|
||||
over("report-chat/$chat")
|
||||
},
|
||||
)
|
||||
}
|
||||
// A report's conversation: the ordinary chat screen, entered from the report and
|
||||
// left back to it. It is not among the chats (the server keeps it under Reports),
|
||||
// so nothing here puts it into the drawer's list either.
|
||||
composable("report-chat/{id}") { e ->
|
||||
val id = e.arguments?.getString("id")
|
||||
ChatScreen(
|
||||
chatId = id,
|
||||
onMenu = { nav.popBackStack() },
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { nav.popBackStack() },
|
||||
report = reportTitles[id].orEmpty(),
|
||||
onFiles = filesAt,
|
||||
)
|
||||
}
|
||||
composable("scheduled") {
|
||||
ScheduledScreen(
|
||||
onBack = { nav.popBackStack() },
|
||||
@@ -297,6 +378,7 @@ class MainActivity : ComponentActivity() {
|
||||
onBack = { nav.popBackStack() },
|
||||
onEdit = { over("schedule-edit/$it") },
|
||||
onOpenRun = { run -> over("schedule/$id/run/$run") },
|
||||
onOpenReport = { report -> over("report/$report") },
|
||||
)
|
||||
}
|
||||
composable("schedule/{id}/run/{run}") { e ->
|
||||
@@ -305,6 +387,7 @@ class MainActivity : ComponentActivity() {
|
||||
e.arguments?.getString("run").orEmpty(),
|
||||
onBack = { nav.popBackStack() },
|
||||
onOpenChat = { top("chat/$it") },
|
||||
onOpenReport = { over("report/$it") },
|
||||
)
|
||||
}
|
||||
composable("schedule-new") {
|
||||
@@ -316,7 +399,7 @@ class MainActivity : ComponentActivity() {
|
||||
ScheduleEditScreen(e.arguments?.getString("id"), onBack = { nav.popBackStack() }, onSaved = { nav.popBackStack() })
|
||||
}
|
||||
composable("settings") {
|
||||
SettingsScreen(onBack = { nav.popBackStack() }, onAddInstance = { over("add") })
|
||||
SettingsScreen(onBack = { nav.popBackStack() }, onAddInstance = { over("add") }, onMcp = { over("mcp") })
|
||||
}
|
||||
// Signing in to one more instance makes it the one in use, which starts a
|
||||
// fresh navigation for it (the `key` above).
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
package eu.llembas.android.actions
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* Carries out a phone action the person confirmed: [run] picks the way -- one intent, the torch, a
|
||||
* media key, or a navigation app -- and answers with done, failed (and why), never silence.
|
||||
*/
|
||||
object ActionRunner {
|
||||
// The reasons go back to the model as the tool's result, so they are written for it, in English.
|
||||
private const val NOT_POSSIBLE = "the phone cannot do this action with these arguments"
|
||||
private const val NO_NAV_APP = "no navigation app chosen or installed (Google Maps or OsmAnd)"
|
||||
private const val NO_DESTINATION =
|
||||
"a stop can only be added with the route's destination: name it (destination), or the person lets LLeMbas ask OsmAnd for it"
|
||||
private const val GOOGLE_CANNOT_STOP = "Google Maps cannot be told to stop navigating; the person stops it there"
|
||||
private const val OSMAND_NEEDS_COORDINATES = "OsmAnd takes a route through stops only with every point's lat and lon"
|
||||
|
||||
/**
|
||||
* [askOsmAnd]: Settings › Phone actions says the person allowed LLeMbas inside OsmAnd, so its
|
||||
* position and the running route's destination may be asked for (`get_info`).
|
||||
*/
|
||||
suspend fun run(context: Context, action: String, args: Args, nav: NavApp?, askOsmAnd: Boolean = false): ActionOutcome {
|
||||
when (action) {
|
||||
"torch" -> return PhoneActions.torch(context, args.bool("on"))
|
||||
"media" -> return PhoneActions.media(context, args.str("command").ifBlank { "toggle" })
|
||||
"navigate", "add_stop", "search_nearby", "stop_navigation" -> return navigate(context, action, args, nav, askOsmAnd)
|
||||
}
|
||||
val intent = PhoneActions.intentFor(context, action, args)
|
||||
?: return ActionOutcome(ActionStatus.Failed, NOT_POSSIBLE)
|
||||
return PhoneActions.launch(context, intent, broadcast = action == "automation_intent")
|
||||
}
|
||||
|
||||
private suspend fun navigate(context: Context, action: String, args: Args, nav: NavApp?, askOsmAnd: Boolean): ActionOutcome {
|
||||
val app = nav ?: return ActionOutcome(ActionStatus.Failed, NO_NAV_APP)
|
||||
val pkg = app.installed(context) ?: return ActionOutcome(ActionStatus.Failed, NO_NAV_APP)
|
||||
val travel = Travel.of(args.str("mode").ifBlank { null })
|
||||
// OsmAnd's own position and destination, if the person allowed LLeMbas to ask it.
|
||||
val info = if (app == NavApp.OsmAnd && askOsmAnd && action != "stop_navigation") osmandInfo(context, pkg) else null
|
||||
val step = when (action) {
|
||||
"navigate" -> args.place("destination")?.let {
|
||||
NavIntents.navigate(app, pkg, it, args.places("stops"), travel, info, replace = args.bool("replace_route") == true)
|
||||
}
|
||||
|
||||
"add_stop" -> args.place("stop")?.let {
|
||||
NavIntents.addStop(app, pkg, it, args.place("destination"), travel, info, NO_DESTINATION)
|
||||
}
|
||||
|
||||
"search_nearby" -> args.str("query").takeIf { it.isNotBlank() }?.let {
|
||||
NavIntents.searchNearby(
|
||||
app,
|
||||
pkg,
|
||||
it,
|
||||
info,
|
||||
alongRoute =
|
||||
args.str("near") == "route",
|
||||
)
|
||||
}
|
||||
|
||||
else -> NavIntents.stop(app, pkg, GOOGLE_CANNOT_STOP)
|
||||
} ?: return ActionOutcome(ActionStatus.Failed, NOT_POSSIBLE)
|
||||
return when (step) {
|
||||
is NavStep.Unsupported -> ActionOutcome(ActionStatus.Failed, step.reason.ifBlank { OSMAND_NEEDS_COORDINATES })
|
||||
|
||||
// The map app comes to the front and stays: it answers nothing more until the person
|
||||
// leaves it, so its having taken the intent is "done".
|
||||
is NavStep.Launch -> PhoneActions.launch(context, step.intent)
|
||||
}
|
||||
}
|
||||
|
||||
/** OsmAnd's `get_info`, when the person allowed it inside OsmAnd; null otherwise, quietly. */
|
||||
private suspend fun osmandInfo(context: Context, pkg: String): OsmAndInfo? {
|
||||
val (code, extras) = forResult(context, NavIntents.osmandInfo(pkg), timeoutMs = 4_000) ?: return null
|
||||
return if (code == Activity.RESULT_OK) OsmAndInfo.of(extras) else null
|
||||
}
|
||||
|
||||
private val waiting = ConcurrentHashMap<Int, CompletableDeferred<Pair<Int, Bundle?>>>()
|
||||
private val ids = AtomicInteger()
|
||||
|
||||
/**
|
||||
* Start [intent] for its result through [ResultActivity] -- a see-through activity of the
|
||||
* app's own, so this works from the assistant's sheet (a voice-interaction session) as well.
|
||||
*/
|
||||
suspend fun forResult(context: Context, intent: Intent, timeoutMs: Long = 60_000): Pair<Int, Bundle?>? {
|
||||
val id = ids.incrementAndGet()
|
||||
val answer = CompletableDeferred<Pair<Int, Bundle?>>()
|
||||
waiting[id] = answer
|
||||
return try {
|
||||
context.startActivity(
|
||||
Intent(context, ResultActivity::class.java)
|
||||
.putExtra(ResultActivity.EXTRA_ID, id)
|
||||
.putExtra(ResultActivity.EXTRA_INTENT, intent)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
withTimeoutOrNull(timeoutMs) { answer.await() }
|
||||
} finally {
|
||||
waiting.remove(id)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun answered(id: Int, code: Int, extras: Bundle?) {
|
||||
waiting[id]?.complete(code to extras)
|
||||
}
|
||||
|
||||
/** Asks another app for a result on [ActionRunner]'s behalf, then goes. Shows nothing of its own. */
|
||||
class ResultActivity : ComponentActivity() {
|
||||
private var id = 0
|
||||
private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
||||
answered(id, result.resultCode, result.data?.extras)
|
||||
finish()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
id = intent.getIntExtra(EXTRA_ID, 0)
|
||||
if (savedInstanceState != null) return
|
||||
@Suppress("DEPRECATION")
|
||||
val target = intent.getParcelableExtra<Intent>(EXTRA_INTENT)
|
||||
if (target == null) {
|
||||
answered(id, Activity.RESULT_CANCELED, null)
|
||||
finish()
|
||||
return
|
||||
}
|
||||
try {
|
||||
launcher.launch(target)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
answered(id, Activity.RESULT_FIRST_USER, null)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_ID = "eu.llembas.android.RESULT_ID"
|
||||
const val EXTRA_INTENT = "eu.llembas.android.RESULT_INTENT"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package eu.llembas.android.actions
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
|
||||
/** A place for a navigation app: coordinates when the model knows them, else words to search for. */
|
||||
data class Place(val name: String = "", val lat: Double? = null, val lon: Double? = null, val query: String = "") {
|
||||
val hasCoordinates: Boolean get() = lat != null && lon != null
|
||||
val label: String get() = name.ifBlank { query.ifBlank { if (hasCoordinates) "$lat, $lon" else "" } }
|
||||
|
||||
/** What a map app searches for: the words, else the name. */
|
||||
val searchText: String get() = query.ifBlank { name }
|
||||
}
|
||||
|
||||
/** The navigation apps the phone actions drive. */
|
||||
enum class NavApp(val id: String, val packages: List<String>) {
|
||||
GoogleMaps("google", listOf("com.google.android.apps.maps")),
|
||||
|
||||
// OsmAnd: `net.osmand.plus` is OsmAnd+ and the F-Droid build (OsmAnd~); `net.osmand` the free one.
|
||||
OsmAnd("osmand", listOf("net.osmand.plus", "net.osmand", "net.osmand.dev")),
|
||||
;
|
||||
|
||||
/** The package of this app on the phone, if it is installed. */
|
||||
fun installed(context: Context): String? = packages.firstOrNull { isInstalled(context, it) }
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Settings' choice among [installed]: the one named; by default whichever is installed, and
|
||||
* with both installed (or "ask"), null -- the card then offers each.
|
||||
*/
|
||||
fun chosen(pref: String, installed: List<NavApp>): NavApp? = when (pref) {
|
||||
PREF_ASK -> null
|
||||
"" -> installed.singleOrNull()
|
||||
else -> installed.firstOrNull { it.id == pref } ?: installed.singleOrNull()
|
||||
}
|
||||
|
||||
fun installedApps(context: Context): List<NavApp> = entries.filter { it.installed(context) != null }
|
||||
|
||||
const val PREF_ASK = "ask"
|
||||
|
||||
private fun isInstalled(context: Context, pkg: String): Boolean = runCatching {
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
context.packageManager.getPackageInfo(pkg, PackageManager.PackageInfoFlags.of(0))
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
context.packageManager.getPackageInfo(pkg, 0)
|
||||
}
|
||||
}.isSuccess
|
||||
}
|
||||
}
|
||||
|
||||
/** How a person travels, as the action names it. */
|
||||
enum class Travel(val id: String, val google: String, val googleNav: String, val osmand: String) {
|
||||
Drive("drive", "driving", "d", "car"),
|
||||
Walk("walk", "walking", "w", "pedestrian"),
|
||||
Bike("bike", "bicycling", "b", "bicycle"),
|
||||
Transit("transit", "transit", "d", "public_transport"),
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun of(id: String?): Travel = entries.firstOrNull { it.id == id } ?: Drive
|
||||
}
|
||||
}
|
||||
|
||||
/** One request to a navigation app: an [Intent], or why it cannot be done in that app. */
|
||||
sealed interface NavStep {
|
||||
data class Launch(val intent: Intent) : NavStep
|
||||
|
||||
data class Unsupported(val reason: String) : NavStep
|
||||
}
|
||||
|
||||
/**
|
||||
* What OsmAnd itself says about the route, when the person allowed LLeMbas to ask
|
||||
* (OsmAnd › Plugins › … › the app's "Location" access for its API): the phone's position and the
|
||||
* route's destination. Null when not allowed -- the actions then use what the model gave.
|
||||
*/
|
||||
data class OsmAndInfo(val lat: Double?, val lon: Double?, val destination: Place?) {
|
||||
companion object {
|
||||
fun of(extras: Bundle?): OsmAndInfo? {
|
||||
extras ?: return null
|
||||
fun d(key: String) = if (extras.containsKey(key)) extras.getDouble(key) else null
|
||||
val dLat = d("destination_lat")
|
||||
val dLon = d("destination_lon")
|
||||
return OsmAndInfo(d("lat"), d("lon"), if (dLat != null && dLon != null) Place(lat = dLat, lon = dLon) else null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The intents, per app. Google Maps: a route to a place with up to a few stops (its `dir` URL),
|
||||
* a search near here (`geo:0,0?q=`); it cannot take a stop into a route already running, nor be
|
||||
* told to stop -- adding a stop there starts the route again through the stop. OsmAnd: its intent
|
||||
* API (`osmand.api://`, a URI protocol; no OsmAnd code in this app): navigate, a route through
|
||||
* stops as a GPX passed as data, a search near a position, stop navigation.
|
||||
*/
|
||||
object NavIntents {
|
||||
private const val GOOGLE_STOPS = 9
|
||||
|
||||
/** [replace]: a route already running is replaced without the map app asking first (OsmAnd asks otherwise). */
|
||||
fun navigate(app: NavApp, pkg: String, destination: Place, stops: List<Place>, travel: Travel, info: OsmAndInfo?, replace: Boolean = false): NavStep =
|
||||
when (app) {
|
||||
NavApp.GoogleMaps -> google(pkg, destination, stops, travel)
|
||||
NavApp.OsmAnd -> osmand(pkg, destination, stops, travel, info, if (replace) "true" else "false")
|
||||
}
|
||||
|
||||
/** A stop on the way to the route's destination ([destination] from the model, else OsmAnd's own). */
|
||||
fun addStop(app: NavApp, pkg: String, stop: Place, destination: Place?, travel: Travel, info: OsmAndInfo?, noDestination: String): NavStep {
|
||||
val to = destination?.takeIf { it.hasCoordinates || it.searchText.isNotBlank() } ?: info?.destination ?: return NavStep.Unsupported(noDestination)
|
||||
// Planned again from here: the route being replaced is the one the person asked to change.
|
||||
return navigate(app, pkg, to, listOf(stop), travel, info, replace = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* [alongRoute] searches near the running route; OsmAnd is given the phone's position for both
|
||||
* (its search ranks along the route itself while one runs), Google Maps searches near here.
|
||||
*/
|
||||
fun searchNearby(app: NavApp, pkg: String, query: String, info: OsmAndInfo?, alongRoute: Boolean = false): NavStep = when {
|
||||
app == NavApp.OsmAnd && info?.lat != null && info.lon != null -> NavStep.Launch(
|
||||
osmandUri(
|
||||
pkg,
|
||||
"navigate_search",
|
||||
"dest_search_query" to query,
|
||||
"search_lat" to info.lat.toString(),
|
||||
"search_lon" to info.lon.toString(),
|
||||
"show_search_results" to "true",
|
||||
"force" to "true",
|
||||
),
|
||||
)
|
||||
|
||||
else -> NavStep.Launch(Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(query))).setPackage(pkg))
|
||||
}
|
||||
|
||||
fun stop(app: NavApp, pkg: String, unsupported: String): NavStep = when (app) {
|
||||
NavApp.OsmAnd -> NavStep.Launch(osmandUri(pkg, "stop_navigation"))
|
||||
NavApp.GoogleMaps -> NavStep.Unsupported(unsupported)
|
||||
}
|
||||
|
||||
/** OsmAnd's own account of the route (needs the person's grant inside OsmAnd). */
|
||||
fun osmandInfo(pkg: String): Intent = osmandUri(pkg, "get_info")
|
||||
|
||||
private fun google(pkg: String, destination: Place, stops: List<Place>, travel: Travel): NavStep {
|
||||
if (stops.isEmpty()) {
|
||||
val q = if (destination.hasCoordinates) "${destination.lat},${destination.lon}" else destination.searchText
|
||||
return NavStep.Launch(Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=${Uri.encode(q)}&mode=${travel.googleNav}")).setPackage(pkg))
|
||||
}
|
||||
val url = Uri.parse("https://www.google.com/maps/dir/").buildUpon()
|
||||
.appendQueryParameter("api", "1")
|
||||
.appendQueryParameter("destination", googlePlace(destination))
|
||||
.appendQueryParameter("waypoints", stops.take(GOOGLE_STOPS).joinToString("|") { googlePlace(it) })
|
||||
.appendQueryParameter("travelmode", travel.google)
|
||||
.appendQueryParameter("dir_action", "navigate")
|
||||
.build()
|
||||
return NavStep.Launch(Intent(Intent.ACTION_VIEW, url).setPackage(pkg))
|
||||
}
|
||||
|
||||
private fun googlePlace(p: Place) = if (p.hasCoordinates) "${p.lat},${p.lon}" else p.searchText
|
||||
|
||||
private fun osmand(pkg: String, destination: Place, stops: List<Place>, travel: Travel, info: OsmAndInfo?, force: String): NavStep {
|
||||
val route = stops + destination
|
||||
return when {
|
||||
// Through stops: OsmAnd follows a route given as GPX, which needs every point's coordinates.
|
||||
stops.isNotEmpty() && route.all { it.hasCoordinates } -> NavStep.Launch(
|
||||
osmandUri(pkg, "navigate_gpx", "force" to force).putExtra("data", gpx(route)),
|
||||
)
|
||||
|
||||
stops.isNotEmpty() -> NavStep.Unsupported("")
|
||||
|
||||
destination.hasCoordinates -> NavStep.Launch(
|
||||
osmandUri(
|
||||
pkg,
|
||||
"navigate",
|
||||
"dest_lat" to destination.lat.toString(),
|
||||
"dest_lon" to destination.lon.toString(),
|
||||
"dest_name" to destination.label,
|
||||
"profile" to travel.osmand,
|
||||
"force" to force,
|
||||
),
|
||||
)
|
||||
|
||||
// Words only: OsmAnd searches them near the phone when it says where the phone is,
|
||||
// else its own search opens with them (geo:0,0?q=).
|
||||
info?.lat != null && info.lon != null -> NavStep.Launch(
|
||||
osmandUri(
|
||||
pkg,
|
||||
"navigate_search",
|
||||
"dest_search_query" to destination.searchText,
|
||||
"search_lat" to info.lat.toString(),
|
||||
"search_lon" to info.lon.toString(),
|
||||
"profile" to travel.osmand,
|
||||
"force" to force,
|
||||
),
|
||||
)
|
||||
|
||||
else -> NavStep.Launch(Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(destination.searchText))).setPackage(pkg))
|
||||
}
|
||||
}
|
||||
|
||||
private fun osmandUri(pkg: String, command: String, vararg params: Pair<String, String>): Intent {
|
||||
val uri = Uri.Builder().scheme("osmand.api").authority(command).apply { params.forEach { (k, v) -> appendQueryParameter(k, v) } }.build()
|
||||
return Intent(Intent.ACTION_VIEW, uri).setPackage(pkg)
|
||||
}
|
||||
|
||||
/** A route as GPX 1.1: its points in order, named. */
|
||||
fun gpx(points: List<Place>): String = buildString {
|
||||
append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
|
||||
append("<gpx version=\"1.1\" creator=\"LLeMbas\" xmlns=\"http://www.topografix.com/GPX/1/1\"><rte>")
|
||||
for (p in points) {
|
||||
append("<rtept lat=\"${p.lat}\" lon=\"${p.lon}\"><name>")
|
||||
append(p.label.replace("&", "&").replace("<", "<").replace(">", ">"))
|
||||
append("</name></rtept>")
|
||||
}
|
||||
append("</rte></gpx>\n")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
package eu.llembas.android.actions
|
||||
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.hardware.camera2.CameraCharacteristics
|
||||
import android.hardware.camera2.CameraManager
|
||||
import android.media.AudioManager
|
||||
import android.net.Uri
|
||||
import android.provider.AlarmClock
|
||||
import android.provider.CalendarContract
|
||||
import android.provider.Settings
|
||||
import android.view.KeyEvent
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
import kotlinx.serialization.json.intOrNull
|
||||
import kotlinx.serialization.json.longOrNull
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneId
|
||||
|
||||
/** How a phone action ended, as the tool's result says it. */
|
||||
enum class ActionStatus(val wire: String) { Done("done"), Declined("declined"), Failed("failed") }
|
||||
|
||||
data class ActionOutcome(val status: ActionStatus, val message: String = "")
|
||||
|
||||
/** The arguments of an action, read leniently: a model writes numbers as strings now and then. */
|
||||
class Args(val json: JsonObject) {
|
||||
private val o get() = json
|
||||
|
||||
fun str(key: String): String = (o[key] as? JsonPrimitive)?.takeIf { it.isString || it.booleanOrNull == null }?.content.orEmpty()
|
||||
|
||||
fun int(key: String): Int? = (o[key] as? JsonPrimitive)?.let { it.intOrNull ?: it.content.toIntOrNull() }
|
||||
|
||||
fun long(key: String): Long? = (o[key] as? JsonPrimitive)?.let { it.longOrNull ?: it.content.toLongOrNull() }
|
||||
|
||||
fun bool(key: String): Boolean? = (o[key] as? JsonPrimitive)?.let { it.booleanOrNull ?: it.content.toBooleanStrictOrNull() }
|
||||
|
||||
fun obj(key: String): Args? = (o[key] as? JsonObject)?.let(::Args)
|
||||
|
||||
fun list(key: String): List<JsonElement> = (o[key] as? JsonArray).orEmpty()
|
||||
|
||||
/** A list of strings (or one string, which a model sometimes writes for a list of one). */
|
||||
fun strings(key: String): List<String> = when (val v = o[key]) {
|
||||
is JsonArray -> v.mapNotNull { (it as? JsonPrimitive)?.content?.trim()?.takeIf(String::isNotEmpty) }
|
||||
is JsonPrimitive -> listOfNotNull(v.content.trim().takeIf { it.isNotEmpty() })
|
||||
else -> emptyList()
|
||||
}
|
||||
|
||||
fun place(key: String): Place? = when (val v = o[key]) {
|
||||
is JsonObject -> placeOf(v)
|
||||
is JsonPrimitive -> v.content.takeIf { it.isNotBlank() }?.let { Place(query = it) }
|
||||
else -> null
|
||||
}
|
||||
|
||||
fun places(key: String): List<Place> = list(key).mapNotNull { e ->
|
||||
when (e) {
|
||||
is JsonObject -> placeOf(e)
|
||||
is JsonPrimitive -> e.content.takeIf { it.isNotBlank() }?.let { Place(query = it) }
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun placeOf(v: JsonObject): Place {
|
||||
fun d(k: String) = (v[k] as? JsonPrimitive)?.let { it.doubleOrNull ?: it.content.toDoubleOrNull() }
|
||||
return Place(
|
||||
name = (v["name"] as? JsonPrimitive)?.content.orEmpty(),
|
||||
lat = d("lat"),
|
||||
lon = d("lon"),
|
||||
query = (v["query"] as? JsonPrimitive)?.content.orEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
/** A time the model wrote: `YYYY-MM-DDTHH:MM` in the phone's zone, `YYYY-MM-DD`, or with an offset. */
|
||||
fun time(key: String): Long? {
|
||||
val raw = str(key).ifBlank { return null }
|
||||
val zone = ZoneId.systemDefault()
|
||||
return runCatching { LocalDateTime.parse(raw).atZone(zone).toInstant().toEpochMilli() }.getOrNull()
|
||||
?: runCatching { LocalDate.parse(raw).atStartOfDay(zone).toInstant().toEpochMilli() }.getOrNull()
|
||||
?: runCatching { OffsetDateTime.parse(raw).toInstant().toEpochMilli() }.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone actions a model may propose (`phone_action`), carried out with Android's standard
|
||||
* intents once the person tapped Do it on the card. Each one either opens the app that does it,
|
||||
* with everything filled in (an alarm, an event, a draft -- the person sends a message or saves
|
||||
* an event there themselves), or does a small thing at once (the torch, play/pause).
|
||||
*
|
||||
* Nothing here runs without the card's Do it, and none of it from the lock screen. A model's
|
||||
* words are data: a URL opens only for http and https, a broadcast never names a system action,
|
||||
* a phone number goes to the dialler and is never called.
|
||||
*/
|
||||
object PhoneActions {
|
||||
/** Media keys, by the action's `command`. */
|
||||
private val MEDIA = mapOf(
|
||||
"toggle" to KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,
|
||||
"play" to KeyEvent.KEYCODE_MEDIA_PLAY,
|
||||
"pause" to KeyEvent.KEYCODE_MEDIA_PAUSE,
|
||||
"next" to KeyEvent.KEYCODE_MEDIA_NEXT,
|
||||
"previous" to KeyEvent.KEYCODE_MEDIA_PREVIOUS,
|
||||
)
|
||||
|
||||
/** Settings panels, by the action's `panel`. Panels (Android 10+) float over the app; the rest are pages. */
|
||||
private val PANELS = mapOf(
|
||||
"wifi" to Settings.Panel.ACTION_WIFI,
|
||||
"internet" to Settings.Panel.ACTION_INTERNET_CONNECTIVITY,
|
||||
"nfc" to Settings.Panel.ACTION_NFC,
|
||||
"volume" to Settings.Panel.ACTION_VOLUME,
|
||||
"bluetooth" to Settings.ACTION_BLUETOOTH_SETTINGS,
|
||||
"location" to Settings.ACTION_LOCATION_SOURCE_SETTINGS,
|
||||
"do_not_disturb" to Settings.ACTION_ZEN_MODE_PRIORITY_SETTINGS,
|
||||
)
|
||||
|
||||
/** Tasker's public intent for running a task by its name (its TaskerIntent protocol). */
|
||||
const val TASKER_PACKAGE = "net.dinglisch.android.taskerm"
|
||||
private const val TASKER_ACTION = "net.dinglisch.android.tasker.ACTION_TASK"
|
||||
|
||||
/** The broadcast any other automation app (Automate, MacroDroid, …) can listen for. */
|
||||
const val AUTOMATION_ACTION = "eu.llembas.android.action.AUTOMATION"
|
||||
|
||||
/** A URL the phone may open for a model: web pages only. */
|
||||
fun urlAllowed(url: String): Boolean = url.trim().lowercase().let {
|
||||
(it.startsWith("http://") || it.startsWith("https://")) &&
|
||||
it.substringAfter("://").isNotBlank()
|
||||
}
|
||||
|
||||
/** `HH:MM` as hour and minute, or null. */
|
||||
fun clock(time: String): Pair<Int, Int>? {
|
||||
val m = Regex("^(\\d{1,2}):(\\d{2})$").matchEntire(time.trim()) ?: return null
|
||||
val (h, min) = m.destructured
|
||||
return (h.toInt() to min.toInt()).takeIf { it.first in 0..23 && it.second in 0..59 }
|
||||
}
|
||||
|
||||
/** SMS recipients: the numbers among [to]; a name the messaging app has to find is left to the person. */
|
||||
fun smsNumbers(to: List<String>): List<String> = to.map { it.trim() }.filter { Regex("^[+0-9 ()./#*-]{3,}$").matches(it) && it.count(Char::isDigit) >= 3 }
|
||||
|
||||
/**
|
||||
* The intent for an action that is one intent (everything but navigation, the torch and media
|
||||
* keys), or null when [action] is not one of these or its arguments do not make one.
|
||||
*/
|
||||
fun intentFor(context: Context, action: String, a: Args): Intent? = when (action) {
|
||||
"alarm" -> clock(a.str("time"))?.let { (hour, minute) ->
|
||||
Intent(AlarmClock.ACTION_SET_ALARM)
|
||||
.putExtra(AlarmClock.EXTRA_HOUR, hour)
|
||||
.putExtra(AlarmClock.EXTRA_MINUTES, minute)
|
||||
.apply { a.str("label").takeIf { it.isNotBlank() }?.let { putExtra(AlarmClock.EXTRA_MESSAGE, it) } }
|
||||
.apply {
|
||||
val days = a.strings("days").mapNotNull(::calendarDay)
|
||||
if (days.isNotEmpty()) putIntegerArrayListExtra(AlarmClock.EXTRA_DAYS, ArrayList(days))
|
||||
}
|
||||
}
|
||||
|
||||
"timer" -> a.int("seconds")?.let { seconds ->
|
||||
Intent(AlarmClock.ACTION_SET_TIMER)
|
||||
.putExtra(AlarmClock.EXTRA_LENGTH, seconds.coerceIn(1, 86_400))
|
||||
.putExtra(AlarmClock.EXTRA_SKIP_UI, false)
|
||||
.apply { a.str("label").takeIf { it.isNotBlank() }?.let { putExtra(AlarmClock.EXTRA_MESSAGE, it) } }
|
||||
}
|
||||
|
||||
// The calendar's new-event screen, filled in: the person saves it.
|
||||
"calendar_event" -> Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI)
|
||||
.putExtra(CalendarContract.Events.TITLE, a.str("title"))
|
||||
.apply {
|
||||
a.time("start")?.let { putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, it) }
|
||||
a.time("end")?.let { putExtra(CalendarContract.EXTRA_EVENT_END_TIME, it) }
|
||||
if (a.bool("all_day") == true) putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true)
|
||||
a.str("location").takeIf { it.isNotBlank() }?.let { putExtra(CalendarContract.Events.EVENT_LOCATION, it) }
|
||||
a.str("notes").takeIf { it.isNotBlank() }?.let { putExtra(CalendarContract.Events.DESCRIPTION, it) }
|
||||
}
|
||||
|
||||
// A draft: the messaging app opens with it, and the person sends.
|
||||
"sms_draft" -> Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + smsNumbers(a.strings("to")).joinToString(";") { Uri.encode(it) }))
|
||||
.putExtra("sms_body", a.str("body"))
|
||||
|
||||
"email_draft" -> Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"))
|
||||
.putExtra(Intent.EXTRA_EMAIL, a.strings("to").toTypedArray())
|
||||
.putExtra(Intent.EXTRA_CC, a.strings("cc").toTypedArray())
|
||||
.putExtra(Intent.EXTRA_SUBJECT, a.str("subject"))
|
||||
.putExtra(Intent.EXTRA_TEXT, a.str("body"))
|
||||
|
||||
// The dialler with the number in it: the person places the call.
|
||||
"dial" -> Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Uri.encode(a.str("number"))))
|
||||
|
||||
"open_url" -> a.str("url").trim().takeIf(::urlAllowed)?.let { Intent(Intent.ACTION_VIEW, Uri.parse(it)) }
|
||||
|
||||
"open_app" -> appIntent(context, "", a.str("app"))
|
||||
|
||||
"settings_panel" -> PANELS[a.str("panel")]?.let { Intent(it) }
|
||||
|
||||
// Tasker (by default) runs the task by its name, the values as its local variables; any
|
||||
// other automation app gets LLeMbas's own broadcast, with the task's name and the values.
|
||||
"automation_intent" -> {
|
||||
val task = a.str("task")
|
||||
val app = a.str("app").trim()
|
||||
val values = a.obj("values")?.json.orEmpty().mapNotNull { (k, v) -> (v as? JsonPrimitive)?.let { k to it.content } }
|
||||
if (app.isBlank() || app.equals("tasker", ignoreCase = true)) {
|
||||
Intent(TASKER_ACTION)
|
||||
.setPackage(TASKER_PACKAGE)
|
||||
.putExtra("version_number", "1.1")
|
||||
.putExtra("task_name", task)
|
||||
.putExtra("task_priority", 5)
|
||||
.putStringArrayListExtra("varNames", ArrayList(values.map { "%" + it.first.lowercase() }))
|
||||
.putStringArrayListExtra("varValues", ArrayList(values.map { it.second }))
|
||||
} else {
|
||||
Intent(AUTOMATION_ACTION)
|
||||
.putExtra("task", task)
|
||||
.putExtra("app", app)
|
||||
.apply { values.forEach { (k, v) -> putExtra(k, v) } }
|
||||
}
|
||||
}
|
||||
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** An app by its package, else by the name the launcher shows (the first app whose label matches). */
|
||||
fun appIntent(context: Context, pkg: String, name: String): Intent? {
|
||||
val pm = context.packageManager
|
||||
pkg.takeIf { it.isNotBlank() }?.let { p -> pm.getLaunchIntentForPackage(p)?.let { return it } }
|
||||
if (name.isBlank()) return null
|
||||
val launcher = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
val apps = runCatching { pm.queryIntentActivities(launcher, PackageManager.MATCH_ALL) }.getOrDefault(emptyList())
|
||||
val wanted = name.trim().lowercase()
|
||||
val found = apps.firstOrNull { it.loadLabel(pm).toString().lowercase() == wanted }
|
||||
?: apps.firstOrNull { it.loadLabel(pm).toString().lowercase().contains(wanted) }
|
||||
?: return null
|
||||
return pm.getLaunchIntentForPackage(found.activityInfo.packageName)
|
||||
}
|
||||
|
||||
/** The torch on or off (or the other way round), through the camera service; no permission needed. */
|
||||
fun torch(context: Context, on: Boolean?): ActionOutcome {
|
||||
val cameras = context.getSystemService(CameraManager::class.java) ?: return ActionOutcome(ActionStatus.Failed, "no camera")
|
||||
val id = cameras.cameraIdList.firstOrNull { cameras.getCameraCharacteristics(it).get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true }
|
||||
?: return ActionOutcome(ActionStatus.Failed, "this phone has no torch")
|
||||
val target = on ?: !torchOn
|
||||
return runCatching {
|
||||
cameras.setTorchMode(id, target)
|
||||
torchOn = target
|
||||
ActionOutcome(ActionStatus.Done, if (target) "torch on" else "torch off")
|
||||
}.getOrElse { ActionOutcome(ActionStatus.Failed, it.message.orEmpty()) }
|
||||
}
|
||||
|
||||
@Volatile
|
||||
private var torchOn = false
|
||||
|
||||
/** A media key to whatever is playing. */
|
||||
fun media(context: Context, key: String): ActionOutcome {
|
||||
val code = MEDIA[key] ?: return ActionOutcome(ActionStatus.Failed, "unknown media command: $key")
|
||||
val audio = context.getSystemService(AudioManager::class.java) ?: return ActionOutcome(ActionStatus.Failed, "no audio")
|
||||
audio.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, code))
|
||||
audio.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_UP, code))
|
||||
return ActionOutcome(ActionStatus.Done, key)
|
||||
}
|
||||
|
||||
/** Start [intent] as a new task; whether an app took it. */
|
||||
fun launch(context: Context, intent: Intent, broadcast: Boolean = false): ActionOutcome = try {
|
||||
if (broadcast) {
|
||||
context.sendBroadcast(intent)
|
||||
} else {
|
||||
context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
ActionOutcome(ActionStatus.Done)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
ActionOutcome(ActionStatus.Failed, "no app on this phone does that")
|
||||
} catch (e: SecurityException) {
|
||||
ActionOutcome(ActionStatus.Failed, e.message.orEmpty())
|
||||
}
|
||||
|
||||
private fun calendarDay(day: String): Int? = when (day.lowercase().take(3)) {
|
||||
"sun" -> java.util.Calendar.SUNDAY
|
||||
"mon" -> java.util.Calendar.MONDAY
|
||||
"tue" -> java.util.Calendar.TUESDAY
|
||||
"wed" -> java.util.Calendar.WEDNESDAY
|
||||
"thu" -> java.util.Calendar.THURSDAY
|
||||
"fri" -> java.util.Calendar.FRIDAY
|
||||
"sat" -> java.util.Calendar.SATURDAY
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import kotlinx.serialization.json.put
|
||||
import kotlinx.serialization.serializer
|
||||
import okhttp3.Call
|
||||
@@ -22,6 +26,7 @@ import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.Response
|
||||
import java.io.IOException
|
||||
import java.io.OutputStream
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
@@ -107,12 +112,19 @@ private fun agentsJson(agents: AgentsSetting) = buildJsonObject {
|
||||
|
||||
internal fun detail(response: Response): String {
|
||||
val text = runCatching { response.body?.string().orEmpty() }.getOrDefault("")
|
||||
val said = runCatching {
|
||||
LembasJson.parseToJsonElement(text).let { it as JsonObject }["detail"]?.jsonPrimitive?.content
|
||||
}.getOrNull()
|
||||
return said ?: "The server answered ${response.code}."
|
||||
return refusal(text) ?: "The server answered ${response.code}."
|
||||
}
|
||||
|
||||
/**
|
||||
* The server's own sentence in a refusal's body: `detail` on `/api/v2`, and OpenAI's shape
|
||||
* (`error.message`) on `/v1`, where speech lives. Null when the body says neither.
|
||||
*/
|
||||
internal fun refusal(body: String): String? = runCatching {
|
||||
val said = LembasJson.parseToJsonElement(body) as JsonObject
|
||||
fun words(of: Any?): String? = (of as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content?.ifBlank { null }
|
||||
words(said["detail"]) ?: words((said["error"] as? JsonObject)?.get("message"))
|
||||
}.getOrNull()
|
||||
|
||||
/**
|
||||
* Everything the app asks one instance, with its token. Every call is the server's
|
||||
* `/api/v2` (or `/v1` for speech), and every refusal comes back as an [ApiException]
|
||||
@@ -146,12 +158,19 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
|
||||
suspend fun models(chatId: String? = null): List<ModelInfo> = modelList(chatId).models
|
||||
|
||||
/** The models with the instance's subagent cap; with [chatId], whether each is offered subagents on that chat. */
|
||||
suspend fun modelList(chatId: String? = null): ModelList = get(if (chatId != null) "/models?chat=$chatId" else "/models")
|
||||
/**
|
||||
* The models with the instance's subagent cap; with [chatId], whether each is offered subagents
|
||||
* on that chat. Only models a chat can be on (`capability` `chat`): this list is what every
|
||||
* picker and the assistant's model setting are filled from.
|
||||
*/
|
||||
suspend fun modelList(chatId: String? = null): ModelList = get<ModelList>(if (chatId != null) "/models?chat=$chatId" else "/models").forChat()
|
||||
|
||||
/** The models for a new agent chat on [deviceId], with whether it may have subagents (`agent_subagents`). */
|
||||
suspend fun agentModelList(deviceId: String?): ModelList =
|
||||
get("/models?kind=agent" + deviceId?.let { "&device=" + java.net.URLEncoder.encode(it, "UTF-8") }.orEmpty())
|
||||
suspend fun agentModelList(deviceId: String?, directory: String? = null): ModelList = get<ModelList>(
|
||||
"/models?kind=agent" + deviceId?.let { "&device=" + segment(it) }.orEmpty() +
|
||||
// With a directory (spec 3.9.0) the answer carries `start`: the model a chat there starts on.
|
||||
directory?.takeIf { deviceId != null && it.isNotBlank() }?.let { "&directory=" + segment(it.trim()) }.orEmpty(),
|
||||
).forChat()
|
||||
|
||||
suspend fun folders(): List<Folder> = get<FolderList>("/folders").folders
|
||||
|
||||
@@ -174,6 +193,37 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
/** The app releases this server recommends; 404 from a server older than the route. */
|
||||
suspend fun apps(): AppsInfo = get("/apps")
|
||||
|
||||
/**
|
||||
* What `@` offers in an agent chat: the device's files matching [q], from the chat's
|
||||
* directory ([chatId]) or, before the chat exists, from the folder chosen for it ([cwd]).
|
||||
*/
|
||||
suspend fun deviceFiles(deviceId: String, q: String, chatId: String? = null, cwd: String? = null): DeviceFiles = get(
|
||||
"/devices/${segment(deviceId)}/files?q=${segment(q)}" +
|
||||
chatId?.let { "&chat=${segment(it)}" }.orEmpty() +
|
||||
cwd?.takeIf { chatId == null && it.isNotBlank() }?.let { "&cwd=${segment(it.trim())}" }.orEmpty(),
|
||||
)
|
||||
|
||||
/** What `@` offers from the server for [q]: the chat's earlier attachments, files of the tree, a web address. */
|
||||
suspend fun mentions(q: String, chatId: String? = null): Mentions = get("/mentions?q=${segment(q)}" + (chatId?.let { "&chat=${segment(it)}" } ?: ""))
|
||||
|
||||
/**
|
||||
* Attach without uploading: a copy of an earlier attachment, a file of the tree as it is now,
|
||||
* or a web page's text -- whichever [mention] is. 404 for what cannot be reached, 400 for a
|
||||
* page that cannot be fetched.
|
||||
*/
|
||||
suspend fun attachFrom(mention: Mention, chatId: String? = null): Attachment = send<AttachmentEnvelope>(
|
||||
"POST",
|
||||
"/attachments/from",
|
||||
buildJsonObject {
|
||||
when (mention.kind) {
|
||||
"attachment" -> put("attachment", mention.id)
|
||||
"url" -> put("url", mention.url)
|
||||
else -> put("path", mention.path)
|
||||
}
|
||||
chatId?.let { put("chat", it) }
|
||||
},
|
||||
).attachment
|
||||
|
||||
/** The web's search in JSON: chats by their words (and meaning, where indexed), files, memories. */
|
||||
suspend fun search(q: String, within: String = "all", limit: Int = 20): SearchResults = get("/search?q=${segment(q)}&in=${segment(within)}&limit=$limit")
|
||||
|
||||
@@ -198,6 +248,14 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
|
||||
suspend fun devices(): List<LinkedDevice> = get<DeviceList>("/devices").devices
|
||||
|
||||
/**
|
||||
* A directory on a linked device, for choosing where an agent chat or an Agentic schedule
|
||||
* works; without a [path], the device's places. No listing is still an answer: its `code`
|
||||
* and `error` say why.
|
||||
*/
|
||||
suspend fun deviceDirectories(deviceId: String, path: String? = null): DeviceDirectory =
|
||||
get("/devices/${segment(deviceId)}/directories" + path?.takeIf { it.isNotEmpty() }?.let { "?path=" + segment(it) }.orEmpty())
|
||||
|
||||
/** The token revokes itself (`lembas logout`'s route). */
|
||||
suspend fun signOut() = empty(authed("$base/api/v1/token").delete().build())
|
||||
|
||||
@@ -239,6 +297,7 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
agents?.let { put("agents", agentsJson(it)) }
|
||||
put("temporary", temporary)
|
||||
forceTool?.let { put("force_tool", it) }
|
||||
put("client", CAPABILITIES)
|
||||
// An agent chat runs on a linked device; an empty directory is the device's first
|
||||
// allowed one. A device that is no longer linked makes it an ordinary chat on the
|
||||
// server, rather than losing the message.
|
||||
@@ -258,6 +317,7 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
put("text", text)
|
||||
put("attachments", JsonArray(attachments.map { JsonPrimitive(it) }))
|
||||
forceTool?.let { put("force_tool", it) }
|
||||
put("client", CAPABILITIES)
|
||||
},
|
||||
)
|
||||
|
||||
@@ -271,14 +331,33 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
suspend fun stop(chatId: String, messageId: String) =
|
||||
empty(authed("$v2/chats/$chatId/messages/$messageId/stop").post(ByteArray(0).toRequestBody(null)).build())
|
||||
|
||||
suspend fun edit(chatId: String, messageId: String, text: String): Turn =
|
||||
send("POST", "/chats/$chatId/messages/$messageId/edit", buildJsonObject { put("text", text) })
|
||||
// Every request that can start a reply says what this app can do, as a message does: the
|
||||
// server then knows who the reply is written for however it was asked for.
|
||||
suspend fun edit(chatId: String, messageId: String, text: String): Turn = send(
|
||||
"POST",
|
||||
"/chats/$chatId/messages/$messageId/edit",
|
||||
buildJsonObject {
|
||||
put("text", text)
|
||||
put("client", CAPABILITIES)
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun regenerate(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/$messageId/regenerate", null)
|
||||
/**
|
||||
* Send a message that waits (`queued`) now: the message as it is after, and the reply started
|
||||
* for it, as a message sent answers. 409 in the instance's words while a reply is being
|
||||
* written in the chat, and when the message no longer waits.
|
||||
*/
|
||||
suspend fun sendWaiting(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/${segment(messageId)}/send", DECLARED)
|
||||
|
||||
suspend fun continueChat(chatId: String): Turn = send("POST", "/chats/$chatId/continue", null)
|
||||
/** Withdraw a message that waits: its row is gone. 409 in words when it no longer waits, 404 when it is not there. */
|
||||
suspend fun discardWaiting(chatId: String, messageId: String): Discarded =
|
||||
call(authed("$v2/chats/$chatId/messages/${segment(messageId)}/discard").post(emptyBody()).build(), Discarded.serializer())
|
||||
|
||||
suspend fun executePlan(chatId: String): Turn = send("POST", "/chats/$chatId/plan/execute", null)
|
||||
suspend fun regenerate(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/$messageId/regenerate", DECLARED)
|
||||
|
||||
suspend fun continueChat(chatId: String): Turn = send("POST", "/chats/$chatId/continue", DECLARED)
|
||||
|
||||
suspend fun executePlan(chatId: String): Turn = send("POST", "/chats/$chatId/plan/execute", DECLARED)
|
||||
|
||||
suspend fun answer(chatId: String, cardId: String, answer: CardAnswer) {
|
||||
val body = LembasJson.encodeToString(CardAnswer.serializer(), answer).toRequestBody(JSON)
|
||||
@@ -348,13 +427,65 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
* Save what the compile made of [words]: a new schedule (201), or with [id] the one being
|
||||
* edited. The words go along as the schedule's `request`, so editing starts from them.
|
||||
*/
|
||||
suspend fun saveSchedule(compiled: ScheduleCompiled, words: String, id: String? = null): Schedule {
|
||||
suspend fun saveSchedule(
|
||||
compiled: ScheduleCompiled,
|
||||
words: String,
|
||||
id: String? = null,
|
||||
notify: String? = null,
|
||||
notifyWhen: String = "",
|
||||
where: WhereToRun = WhereToRun.Leave,
|
||||
model: String? = null,
|
||||
watch: WatchCommand? = null,
|
||||
): Schedule {
|
||||
val body = buildJsonObject {
|
||||
// The type (spec 3.9.0): Agentic is a schedule with a computer, Chat one without. Left
|
||||
// out where the form did not say, so a schedule is never moved by a form that did not read it.
|
||||
when (where) {
|
||||
WhereToRun.Leave -> Unit
|
||||
|
||||
WhereToRun.Server -> put("runs_on", JsonNull)
|
||||
|
||||
is WhereToRun.Computer -> {
|
||||
put(
|
||||
"runs_on",
|
||||
buildJsonObject {
|
||||
put("device", where.device)
|
||||
put("cwd", where.cwd)
|
||||
put("mode", where.mode)
|
||||
where.approvalWaitMinutes?.let { put("approval_wait_minutes", it) }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
// The model, where the form says one: empty is the folder's usual model for an
|
||||
// Agentic schedule, asked of the computer as each run starts.
|
||||
model?.let { put("model", it) }
|
||||
// The watched command, where the form says one: none at all is "watch nothing".
|
||||
watch?.let { said ->
|
||||
if (said.command.isBlank()) {
|
||||
put("watch", JsonNull)
|
||||
} else {
|
||||
put(
|
||||
"watch",
|
||||
buildJsonObject {
|
||||
put("kind", "command")
|
||||
put("command", said.command)
|
||||
said.timeoutS?.let { put("timeout_s", it) }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
put("title", compiled.title)
|
||||
put("instruction", compiled.instruction)
|
||||
put("rule", compiled.rule)
|
||||
put("target", compiled.target)
|
||||
if (id == null) put("request", words)
|
||||
// Notify when (spec 3.8.0): left out where the form did not say, so an older server is sent nothing new.
|
||||
if (notify != null) {
|
||||
put("notify", notify)
|
||||
// The person's own words, or none: an empty condition is the server's default, in its own words.
|
||||
if (notify == "when") put("notify_when", notifyWhen.trim())
|
||||
}
|
||||
}
|
||||
return if (id == null) {
|
||||
send<ScheduleEnvelope>("POST", "/schedules", body).schedule
|
||||
@@ -363,6 +494,30 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
}
|
||||
}
|
||||
|
||||
// --- Reports (`schedule.use`) ---------------------------------------------------------------
|
||||
|
||||
/** The reports, newest first; [unread] only those not read yet, [schedule] only one schedule's. */
|
||||
suspend fun reports(unread: Boolean = false, schedule: String? = null): List<Report> {
|
||||
val asked = listOfNotNull(if (unread) "unread=1" else null, schedule?.let { "schedule=" + segment(it) }).joinToString("&")
|
||||
return get<ReportList>(if (asked.isEmpty()) "/reports" else "/reports?" + asked).reports
|
||||
}
|
||||
|
||||
/** How many reports are unread: the drawer's badge. */
|
||||
suspend fun unreadReports(): Int = get<ReportList>("/reports?unread=1").unreadCount
|
||||
|
||||
/** One report with its body. Read as the report itself, or as `{report: …}` around it. */
|
||||
suspend fun report(id: String): Report {
|
||||
val answer = get<JsonObject>("/reports/${segment(id)}")
|
||||
return LembasJson.decodeFromJsonElement(Report.serializer(), answer["report"] as? JsonObject ?: answer)
|
||||
}
|
||||
|
||||
suspend fun readReport(id: String) = empty(authed("$v2/reports/${segment(id)}/read").post("{}".toRequestBody(JSON)).build())
|
||||
|
||||
suspend fun deleteReport(id: String) = empty(authed("$v2/reports/${segment(id)}").delete().build())
|
||||
|
||||
/** Continue the report as a conversation: the chat it is in, which stays under Reports. */
|
||||
suspend fun replyToReport(id: String): String? = send<ReportReply>("POST", "/reports/${segment(id)}/reply", null).chatId
|
||||
|
||||
suspend fun pauseSchedule(id: String, paused: Boolean): Schedule =
|
||||
send<ScheduleEnvelope>("POST", "/schedules/${segment(id)}/" + if (paused) "pause" else "resume", null).schedule
|
||||
|
||||
@@ -465,6 +620,241 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
return call(authed(url.toString()).get().build(), FileContent.serializer())
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the file with node id [id] is now, after any rename or move: `GET /api/v2/files/node`.
|
||||
* A file the person may not read and an id that names nothing are the same 404; an instance
|
||||
* from before this route answers a 404 or a 405 of its own ([eu.llembas.android.ui.files.noSuchRoute]).
|
||||
*/
|
||||
suspend fun fileNode(id: String): FileNode = call(authed(filesUrl("/node", "id" to id)).get().build(), FileNode.serializer())
|
||||
|
||||
// --- The file manager's writes, the trash, versions and bytes ---------------------------------
|
||||
// Each write answers the listing of the directory it changed; a refusal is the tree's own
|
||||
// sentence (400), a path that cannot be read a 404, and both come back as an ApiException.
|
||||
|
||||
private fun filesUrl(path: String, vararg query: Pair<String, String?>): String = "$v2/files$path".toHttpUrl().newBuilder()
|
||||
.apply { query.forEach { (name, value) -> if (value != null) addQueryParameter(name, value) } }
|
||||
.build()
|
||||
.toString()
|
||||
|
||||
suspend fun makeFolder(dir: String, name: String): FileListing = send(
|
||||
"POST",
|
||||
"/files/mkdir",
|
||||
buildJsonObject {
|
||||
put("path", dir)
|
||||
put("name", name)
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun renameFile(path: String, name: String): FileListing = send(
|
||||
"POST",
|
||||
"/files/rename",
|
||||
buildJsonObject {
|
||||
put("path", path)
|
||||
put("name", name)
|
||||
},
|
||||
)
|
||||
|
||||
/** Copy [path] into the directory [to]; the answer's `copied` says what the copy is called. */
|
||||
suspend fun copyFile(path: String, to: String, name: String? = null): FileListing = send(
|
||||
"POST",
|
||||
"/files/copy",
|
||||
buildJsonObject {
|
||||
put("path", path)
|
||||
put("to", to)
|
||||
name?.let { put("name", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Move or copy [paths] into the directory [to], or delete them (to the trash): `op` is
|
||||
* `move`, `copy` or `delete`. Each path is done by itself, so the answer is read for what
|
||||
* failed even though the request succeeded.
|
||||
*/
|
||||
suspend fun batchFiles(op: String, paths: List<String>, to: String? = null): BatchAnswer = send(
|
||||
"POST",
|
||||
"/files/batch",
|
||||
buildJsonObject {
|
||||
put("op", op)
|
||||
put("paths", JsonArray(paths.map { JsonPrimitive(it) }))
|
||||
to?.let { put("to", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Save a text file. [base] is the `sha` the file had when it was opened: when it holds
|
||||
* something else by now the server writes nothing and this throws [SaveConflict] with its
|
||||
* sentence, unless [force]. Without a [base] nothing is compared, and a path with no file
|
||||
* makes one. With [create] the file must be new: where something is already at the path the
|
||||
* server writes nothing (409, `exists`) and this throws [FileExists] with its sentence -- an
|
||||
* older server knows no `create` and writes as before.
|
||||
*/
|
||||
suspend fun saveFile(path: String, text: String, base: String? = null, force: Boolean = false, create: Boolean = false): FileContent {
|
||||
val body = buildJsonObject {
|
||||
put("path", path)
|
||||
put("text", text)
|
||||
base?.takeIf { it.isNotBlank() }?.let { put("base", it) }
|
||||
if (force) put("force", true)
|
||||
if (create) put("create", true)
|
||||
}
|
||||
val request = authed("$v2/files/content").put(body.toString().toRequestBody(JSON)).build()
|
||||
return withContext(Dispatchers.IO) { http.newCall(request).await().use { response -> saved(response) } }
|
||||
}
|
||||
|
||||
/**
|
||||
* A new, empty text file called [name] in the directory [dir]; its path. Never over what
|
||||
* is there: `create` has the instance refuse a taken name ([FileExists], its sentence), and
|
||||
* because an instance from before `create` ignores the word and would empty the file, the
|
||||
* directory is read first and a name it holds is refused here, with nothing sent.
|
||||
*/
|
||||
suspend fun newFile(dir: String, name: String): String {
|
||||
val path = FileKinds.child(dir, name)
|
||||
if (files(dir).entries.any { it.name == name.trim() || it.path == path }) throw FileExists("")
|
||||
saveFile(path, "", create = true)
|
||||
return path
|
||||
}
|
||||
|
||||
/** A save's answer: the file as it is now, or what refused it. */
|
||||
private fun saved(response: Response): FileContent {
|
||||
val said = runCatching { response.body?.string().orEmpty() }.getOrDefault("")
|
||||
if (response.code == 409) {
|
||||
val conflict = runCatching { LembasJson.parseToJsonElement(said) as? JsonObject }.getOrNull() ?: JsonObject(emptyMap())
|
||||
if ((conflict["conflict"] as? JsonPrimitive)?.content == "true") {
|
||||
throw SaveConflict(refusal(said).orEmpty(), (conflict["sha"] as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content.orEmpty())
|
||||
}
|
||||
// A new file whose name is taken: nothing was written, and the sentence says what is there.
|
||||
if ((conflict["exists"] as? JsonPrimitive)?.content == "true") throw FileExists(refusal(said).orEmpty())
|
||||
}
|
||||
if (!response.isSuccessful) throw ApiException(response.code, refusal(said) ?: "The server answered ${response.code}.")
|
||||
return LembasJson.decodeFromString(FileContent.serializer(), said)
|
||||
}
|
||||
|
||||
suspend fun trash(): TrashList = get("/files/trash")
|
||||
|
||||
suspend fun restoreTrashed(id: String): TrashList = send("POST", "/files/restore", buildJsonObject { put("id", id) })
|
||||
|
||||
/** Remove for good: the one thing named, or with no [id] everything in the trash. */
|
||||
suspend fun removeTrashed(id: String? = null): TrashList = call(authed(filesUrl("/trash", "id" to id)).delete().build(), TrashList.serializer())
|
||||
|
||||
suspend fun fileVersions(path: String): FileVersions = call(authed(filesUrl("/versions", "path" to path)).get().build(), FileVersions.serializer())
|
||||
|
||||
/** Make an older version the file again, as a new version: nothing is lost. */
|
||||
suspend fun restoreVersion(path: String, version: String): FileVersions = send(
|
||||
"POST",
|
||||
"/files/versions/restore",
|
||||
buildJsonObject {
|
||||
put("path", path)
|
||||
put("version", version)
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Upload one file into the directory [dir], streamed: [body] writes the file's bytes as they
|
||||
* are read, so a large file is never held in memory. A file over the instance's limit is a
|
||||
* 413 whose sentence names it.
|
||||
*/
|
||||
suspend fun uploadFile(dir: String, name: String, body: RequestBody): FileListing {
|
||||
val form = MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("files", name, body).build()
|
||||
return call(authed(filesUrl("/upload", "path" to dir)).post(form).build(), FileListing.serializer())
|
||||
}
|
||||
|
||||
/**
|
||||
* The request for a file's bytes (`/files/raw`), or for [range] of them. The token goes in
|
||||
* the Authorization header, as on every call: the address names the path and nothing else.
|
||||
*/
|
||||
fun rawFile(path: String, range: LongRange? = null, inline: Boolean = false): Request = raw(Raw.Path(path), range, inline)
|
||||
|
||||
/**
|
||||
* The request for [what]'s bytes, or for [range] of them: a file of the tree by its path (one
|
||||
* [Raw.Path.version] of it, where named), a file by its node id wherever it is now, or a chat's
|
||||
* attachment. Always with the token in the header and never in the address.
|
||||
*/
|
||||
fun raw(what: Raw, range: LongRange? = null, inline: Boolean = false): Request = authed(
|
||||
when (what) {
|
||||
is Raw.Path -> filesUrl("/raw", "path" to what.path, "version" to what.version?.ifBlank { null }, "inline" to if (inline) "1" else null)
|
||||
is Raw.Node -> filesUrl("/raw", "node" to what.id, "inline" to if (inline) "1" else null)
|
||||
is Raw.Attached -> "$v2/attachments/${segment(what.id)}"
|
||||
},
|
||||
)
|
||||
.header("Accept", "*/*")
|
||||
.apply { range?.let { header("Range", "bytes=${it.first}-${it.last}") } }
|
||||
.get()
|
||||
.build()
|
||||
|
||||
/** The request for [paths] (files and folders) as one zip. */
|
||||
fun zipFiles(paths: List<String>): Request = authed("$v2/files/zip")
|
||||
.header("Accept", "*/*")
|
||||
.post(buildJsonObject { put("paths", JsonArray(paths.map { JsonPrimitive(it) })) }.toString().toRequestBody(JSON))
|
||||
.build()
|
||||
|
||||
/**
|
||||
* Run [request] and copy what it answers into [out] as it comes, saying how far it is
|
||||
* ([progress]: bytes so far, and the total when the server said one, else -1). At most
|
||||
* [most] bytes are taken: more than that is refused as a 413, with nothing more read.
|
||||
*/
|
||||
suspend fun download(request: Request, out: OutputStream, most: Long = Long.MAX_VALUE, progress: (done: Long, total: Long) -> Unit = { _, _ -> }): Long =
|
||||
withContext(Dispatchers.IO) {
|
||||
val call = http.newCall(request)
|
||||
val finished = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
// A read that waits for the server does not hear that the transfer was given up:
|
||||
// the call is cancelled from beside it, which ends the read at once.
|
||||
val watch = launch(start = CoroutineStart.UNDISPATCHED) {
|
||||
try {
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
if (!finished.get()) call.cancel()
|
||||
}
|
||||
}
|
||||
try {
|
||||
call.await().use { response ->
|
||||
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
||||
val body = response.body ?: throw ApiException(response.code, "")
|
||||
val total = body.contentLength()
|
||||
if (total > most) throw ApiException(413, "")
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var done = 0L
|
||||
body.byteStream().use { stream ->
|
||||
while (true) {
|
||||
ensureActive()
|
||||
val n = stream.read(buffer)
|
||||
if (n < 0) break
|
||||
done += n
|
||||
if (done > most) throw ApiException(413, "")
|
||||
out.write(buffer, 0, n)
|
||||
progress(done, total)
|
||||
}
|
||||
}
|
||||
out.flush()
|
||||
done
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
// The read a cancelled call ends with is the cancelling, not a failure of the network.
|
||||
ensureActive()
|
||||
throw e
|
||||
} finally {
|
||||
// Ended by itself: the watcher is let go, and leaves the finished call alone.
|
||||
finished.set(true)
|
||||
watch.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The bytes `[from, to]` of a file, for a player or a table's first rows: a `Range` request,
|
||||
* blocking, on whatever thread asks (never the main one). A server that answers the whole
|
||||
* file to a range that does not start at 0 is refused rather than read from the wrong place.
|
||||
*/
|
||||
fun rawBytes(path: String, from: Long, to: Long): ByteArray = rawBytes(Raw.Path(path), from, to)
|
||||
|
||||
/** The same for any [Raw]: a file by its node id is read a piece at a time as one by its path is. */
|
||||
fun rawBytes(what: Raw, from: Long, to: Long): ByteArray = http.newCall(raw(what, from..to)).execute().use { response ->
|
||||
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
||||
if (response.code != 206 && from > 0) throw ApiException(416, "")
|
||||
val want = to - from + 1
|
||||
response.body!!.source().use { source ->
|
||||
source.request(want)
|
||||
source.buffer.readByteArray(minOf(source.buffer.size, want))
|
||||
}
|
||||
}
|
||||
|
||||
/** A file of the tree in the web UI's own viewer (`/files/view`), for what the app does not draw. */
|
||||
fun webFile(path: String): String = "$base/files/view".toHttpUrl().newBuilder().addQueryParameter("path", path).build().toString()
|
||||
|
||||
@@ -475,6 +865,21 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
.build()
|
||||
.toString()
|
||||
|
||||
// --- Generated media's jobs, and the MCP servers ----------------------------------------------
|
||||
|
||||
/** A chat's long generations, newest first (at most 50); with [active] only those under way. */
|
||||
suspend fun mediaJobs(chatId: String, active: Boolean = false): List<MediaJob> =
|
||||
get<MediaJobList>("/media/jobs?chat_id=${segment(chatId)}" + if (active) "&active=true" else "").jobs
|
||||
|
||||
/** One job as it stands; somebody else's, or one that is gone, is a 404 in the server's words. */
|
||||
suspend fun mediaJob(id: String): MediaJob = get("/media/jobs/${segment(id)}")
|
||||
|
||||
/** Stop a job: the job as it is after. One that has ended stays what it was, so this is safe to repeat. */
|
||||
suspend fun cancelMediaJob(id: String): MediaJob = call(authed("$v2/media/jobs/${segment(id)}").delete().build(), MediaJob.serializer())
|
||||
|
||||
/** The MCP servers whose tools this person's chats may be offered, and how each is signed in to. */
|
||||
suspend fun mcpServers(): List<McpServer> = get<McpServerList>("/mcp").servers
|
||||
|
||||
// --- Push --------------------------------------------------------------------------------
|
||||
suspend fun pushKey(): PushKey = get("/push")
|
||||
|
||||
@@ -490,22 +895,28 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
suspend fun forgetPush() = empty(authed("$v2/push").delete().build())
|
||||
|
||||
// --- Voice (/v1, the `models` scope) -----------------------------------------------------
|
||||
suspend fun transcribe(wav: ByteArray, language: String? = null): String {
|
||||
|
||||
/**
|
||||
* Write a recording down. [media] says which chat it is for, so that the chat's model's
|
||||
* connection may serve it with its own speech model (server 2.0.0-beta.15); a server before
|
||||
* that reads only the fields it knows and answers from its one endpoint.
|
||||
*/
|
||||
suspend fun transcribe(wav: ByteArray, language: String? = null, media: MediaFor = MediaFor.DEFAULT): Heard = withContext(Dispatchers.IO) {
|
||||
val body = MultipartBody.Builder().setType(MultipartBody.FORM)
|
||||
.addFormDataPart("file", "speech.wav", wav.toRequestBody("audio/wav".toMediaType()))
|
||||
.apply { language?.let { addFormDataPart("language", it) } }
|
||||
.apply { transcriptionFields(language, media).forEach { (name, value) -> addFormDataPart(name, value) } }
|
||||
.build()
|
||||
return call(authed("$base/v1/audio/transcriptions").post(body).build(), Transcript.serializer()).text
|
||||
http.newCall(authed("$base/v1/audio/transcriptions").post(body).build()).await().use {
|
||||
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
|
||||
Heard(LembasJson.decodeFromString(Transcript.serializer(), it.body!!.string()).text, fallbackSource(it))
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun speech(text: String): ByteArray = withContext(Dispatchers.IO) {
|
||||
val body = buildJsonObject {
|
||||
put("input", text.take(20_000))
|
||||
put("response_format", "mp3")
|
||||
}
|
||||
http.newCall(authed("$base/v1/audio/speech").post(body.toString().toRequestBody(JSON)).build()).await().use {
|
||||
/** [text] as speech, for the chat [media] names (see [transcribe]). */
|
||||
suspend fun speech(text: String, media: MediaFor = MediaFor.DEFAULT): Spoken = withContext(Dispatchers.IO) {
|
||||
http.newCall(authed("$base/v1/audio/speech").post(speechBody(text, media).toString().toRequestBody(JSON)).build()).await().use {
|
||||
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
|
||||
it.body!!.bytes()
|
||||
Spoken(it.body!!.bytes(), fallbackSource(it))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -513,9 +924,46 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
authed("$v2/chats/$chatId/messages/$messageId/stream").header("Accept", "text/event-stream").build()
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* What this app can do, sent with every request that can start a reply (spec 3.6.0):
|
||||
* the phone carries out `phone_action` calls the person confirms here, so the chat is
|
||||
* offered the tool -- and a reply for the phone is one without pages to draw.
|
||||
*/
|
||||
private val CAPABILITIES = JsonArray(listOf(JsonPrimitive("phone_actions")))
|
||||
|
||||
/** The body of a request that says nothing else: the declaration alone. */
|
||||
private val DECLARED = JsonObject(mapOf("client" to CAPABILITIES))
|
||||
|
||||
/** 1 MB, the server's own limit on a shown file, with room for a little more. */
|
||||
const val SHOWN_MAX_BYTES = 1_100_000L
|
||||
|
||||
/** The transcription's form fields beside the file: the language, and which chat. */
|
||||
fun transcriptionFields(language: String?, media: MediaFor): List<Pair<String, String>> = buildList {
|
||||
language?.let { add("language" to it) }
|
||||
media.chatId?.let { add("chat_id" to it) }
|
||||
media.chatModel?.let { add("chat_model" to it) }
|
||||
}
|
||||
|
||||
/** The body of a speech request: the words, the format, and which chat. */
|
||||
fun speechBody(text: String, media: MediaFor): JsonObject = buildJsonObject {
|
||||
put("input", text.take(20_000))
|
||||
put("response_format", "mp3")
|
||||
media.chatId?.let { put("chat_id", it) }
|
||||
media.chatModel?.let { put("chat_model", it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The source that answered in place of the chat's own (`X-Lembas-Fallback`), by its name
|
||||
* (`X-Lembas-Source`, percent-encoded: a header is Latin-1); null when the one expected
|
||||
* answered, and from a server that says neither.
|
||||
*/
|
||||
fun fallbackSource(fallback: String?, source: String?): String? {
|
||||
if (fallback.isNullOrBlank() || fallback == "0" || source.isNullOrBlank()) return null
|
||||
return runCatching { java.net.URLDecoder.decode(source.replace("+", "%2B"), "UTF-8") }.getOrDefault(source).ifBlank { null }
|
||||
}
|
||||
|
||||
private fun fallbackSource(response: Response): String? = fallbackSource(response.header("X-Lembas-Fallback"), response.header("X-Lembas-Source"))
|
||||
|
||||
fun emptyBody(): RequestBody = ByteArray(0).toRequestBody(null)
|
||||
|
||||
/** A model's picture is small; anything larger is not one. */
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
// An edit's diff on its approval card, worked out on the phone from the two texts the card
|
||||
// carries (`contract/event_ask_edit.json`). Lines only: what is drawn is text with a sign, and
|
||||
// every step is bounded before it is taken, because both texts are a model's and a file's words
|
||||
// of any size.
|
||||
|
||||
/** What a line of a diff is: in both texts, only in the new one, only in the old one, or the mark of lines left out between two changes. */
|
||||
enum class DiffSign { Same, Added, Removed, Gap }
|
||||
|
||||
data class DiffLine(val sign: DiffSign, val text: String)
|
||||
|
||||
/**
|
||||
* One file's change as the card draws it: the changed lines with a little around them, and how
|
||||
* many were added and removed. [endings] says a change of line endings (`"LF" to "CRLF"`), which
|
||||
* is said once instead of as every line going and coming. [cut]: the texts were longer than what
|
||||
* a phone compares, and only their beginning was.
|
||||
*/
|
||||
data class DiffView(val lines: List<DiffLine>, val added: Int, val removed: Int, val endings: Pair<String, String>? = null, val cut: Boolean = false) {
|
||||
/** The lines drawn: the first [DIFF_FOLD] until the person opens it, and never more than [DIFF_MOST]. */
|
||||
fun shown(open: Boolean): List<DiffLine> = lines.take(if (open) DIFF_MOST else DIFF_FOLD)
|
||||
|
||||
/** Whether there is more than the folded card shows. */
|
||||
val folds: Boolean get() = lines.size > DIFF_FOLD
|
||||
|
||||
/** The lines not drawn even when open. */
|
||||
val beyond: Int get() = (lines.size - DIFF_MOST).coerceAtLeast(0)
|
||||
|
||||
/** Whether the block says anything of the change at all; a card whose diffs say nothing keeps its arguments in view. */
|
||||
val says: Boolean get() = lines.isNotEmpty() || endings != null || cut
|
||||
}
|
||||
|
||||
/** How many lines of a file's diff the card shows before it is opened. */
|
||||
const val DIFF_FOLD = 12
|
||||
|
||||
/** The most lines of one file's diff the card lays out: a card is for deciding, not for reading a megabyte. */
|
||||
const val DIFF_MOST = 400
|
||||
|
||||
/** The lines kept around a change. */
|
||||
const val DIFF_CONTEXT = 3
|
||||
|
||||
/** Past this many pairs of lines the two middles are not compared: the old one is shown going and the new one coming. */
|
||||
private const val DIFF_CELLS = 1_000_000L
|
||||
|
||||
/** The most lines of one text that are compared, and the most characters: what is past either is left out before any work is done. */
|
||||
const val DIFF_TEXT_LINES = 2_000
|
||||
const val DIFF_TEXT_CHARS = 200_000
|
||||
|
||||
/** A text's lines as they are compared, and whether the text went on past what is. */
|
||||
data class TextLines(val lines: List<String>, val cut: Boolean)
|
||||
|
||||
/**
|
||||
* The lines of [text], at most [mostLines] of them from at most its first [mostChars]
|
||||
* characters: nothing past either bound is read, split or kept. The newline that ends the last
|
||||
* line starts no empty one, and a line is compared without the `\r` before its newline, so a
|
||||
* file whose line endings change is not a file whose every line changes.
|
||||
*/
|
||||
fun textLines(text: String, mostLines: Int = DIFF_TEXT_LINES, mostChars: Int = DIFF_TEXT_CHARS): TextLines {
|
||||
val end = minOf(text.length, mostChars)
|
||||
val lines = ArrayList<String>()
|
||||
var from = 0
|
||||
while (from < end && lines.size < mostLines) {
|
||||
val newline = text.indexOf('\n', from).let { if (it < 0 || it >= end) -1 else it }
|
||||
val to = if (newline < 0) end else newline
|
||||
lines += text.substring(from, if (to > from && text[to - 1] == '\r') to - 1 else to)
|
||||
from = if (newline < 0) end else newline + 1
|
||||
}
|
||||
return TextLines(lines, cut = from < text.length)
|
||||
}
|
||||
|
||||
/** How [text]'s lines end, where it has any: `CRLF` when its first newline follows a `\r`, else `LF`; null for a text of one line. */
|
||||
internal fun lineEnding(text: String): String? {
|
||||
val newline = text.indexOf('\n')
|
||||
return when {
|
||||
newline < 0 -> null
|
||||
newline > 0 && text[newline - 1] == '\r' -> "CRLF"
|
||||
else -> "LF"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [old] turned into [new], line by line: what both begin and end with is the same without being
|
||||
* compared, and the middle is the longest run of lines the two share -- or, where the middles
|
||||
* are too long to compare on a phone, the old middle removed and the new one added.
|
||||
*/
|
||||
fun diffLines(old: List<String>, new: List<String>): List<DiffLine> {
|
||||
var head = 0
|
||||
while (head < old.size && head < new.size && old[head] == new[head]) head++
|
||||
var tail = 0
|
||||
while (tail < old.size - head && tail < new.size - head && old[old.size - 1 - tail] == new[new.size - 1 - tail]) tail++
|
||||
val a = old.subList(head, old.size - tail)
|
||||
val b = new.subList(head, new.size - tail)
|
||||
val out = ArrayList<DiffLine>(old.size + b.size)
|
||||
for (i in 0 until head) out += DiffLine(DiffSign.Same, old[i])
|
||||
if (a.isEmpty() || b.isEmpty() || a.size.toLong() * b.size > DIFF_CELLS) {
|
||||
a.forEach { out += DiffLine(DiffSign.Removed, it) }
|
||||
b.forEach { out += DiffLine(DiffSign.Added, it) }
|
||||
} else {
|
||||
// shared[i][j]: how many lines the rest of a from i and the rest of b from j have in common, in order.
|
||||
val shared = Array(a.size + 1) { IntArray(b.size + 1) }
|
||||
for (i in a.size - 1 downTo 0) {
|
||||
for (j in b.size - 1 downTo 0) {
|
||||
shared[i][j] = if (a[i] == b[j]) shared[i + 1][j + 1] + 1 else maxOf(shared[i + 1][j], shared[i][j + 1])
|
||||
}
|
||||
}
|
||||
var i = 0
|
||||
var j = 0
|
||||
while (i < a.size && j < b.size) {
|
||||
when {
|
||||
a[i] == b[j] -> {
|
||||
out += DiffLine(DiffSign.Same, a[i])
|
||||
i++
|
||||
j++
|
||||
}
|
||||
|
||||
shared[i + 1][j] >= shared[i][j + 1] -> out += DiffLine(DiffSign.Removed, a[i++])
|
||||
|
||||
else -> out += DiffLine(DiffSign.Added, b[j++])
|
||||
}
|
||||
}
|
||||
while (i < a.size) out += DiffLine(DiffSign.Removed, a[i++])
|
||||
while (j < b.size) out += DiffLine(DiffSign.Added, b[j++])
|
||||
}
|
||||
for (i in old.size - tail until old.size) out += DiffLine(DiffSign.Same, old[i])
|
||||
return out
|
||||
}
|
||||
|
||||
/** The changed lines of [lines] with [context] unchanged ones around each, and one [DiffSign.Gap] where lines between two changes are left out. */
|
||||
fun hunks(lines: List<DiffLine>, context: Int = DIFF_CONTEXT): List<DiffLine> {
|
||||
val keep = BooleanArray(lines.size)
|
||||
lines.forEachIndexed { at, line ->
|
||||
if (line.sign != DiffSign.Same) for (k in maxOf(0, at - context)..minOf(lines.size - 1, at + context)) keep[k] = true
|
||||
}
|
||||
val out = ArrayList<DiffLine>()
|
||||
var left = false
|
||||
lines.forEachIndexed { at, line ->
|
||||
if (keep[at]) {
|
||||
if (left && out.isNotEmpty()) out += DiffLine(DiffSign.Gap, "")
|
||||
left = false
|
||||
out += line
|
||||
} else {
|
||||
left = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* This file's change for the card: a file that is made is all added, one that goes is all
|
||||
* removed. Bounded before it starts ([textLines]) and while it runs ([diffLines]); it is still
|
||||
* work for a background thread, never for a frame.
|
||||
*/
|
||||
fun FileDiff.view(): DiffView {
|
||||
val before = oldText.orEmpty()
|
||||
val after = if (deleted) "" else newText
|
||||
val old = textLines(before)
|
||||
val new = textLines(after)
|
||||
val all = diffLines(old.lines, new.lines)
|
||||
val from = lineEnding(before)
|
||||
val to = lineEnding(after)
|
||||
return DiffView(
|
||||
hunks(all),
|
||||
added = all.count { it.sign == DiffSign.Added },
|
||||
removed = all.count { it.sign == DiffSign.Removed },
|
||||
endings = if (from != null && to != null && from != to) from to to else null,
|
||||
cut = old.cut || new.cut,
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether an approval's item shows its `detail` (the call's arguments): always without diffs, and with them when none of them says anything. [views] is null while they are worked out. */
|
||||
fun showsDetail(item: CardItem, views: List<DiffView>?): Boolean = item.diffs.isEmpty() || (views != null && views.none { it.says })
|
||||
|
||||
// Characters a person cannot see, or that would move or break a line: on a card where somebody
|
||||
// decides, each is written as its code point.
|
||||
private fun unseen(c: Char): Boolean = when (c.code) {
|
||||
in 0x00..0x1F, in 0x7F..0x9F -> true
|
||||
0x00AD, 0x061C, 0x180E, 0xFEFF -> true
|
||||
in 0x200B..0x200F, in 0x2028..0x202E, in 0x2060..0x206F -> true
|
||||
in 0xFFF9..0xFFFB -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
/**
|
||||
* [text] with every invisible, direction-changing or line-breaking character written as
|
||||
* `<U+202E>`: a bidi override, a zero-width space, a line separator, a control. A tab is four
|
||||
* spaces. What is drawn reads as what is written.
|
||||
*/
|
||||
fun visibly(text: String): String {
|
||||
if (text.none { it == '\t' || unseen(it) }) return text
|
||||
return buildString(text.length + 16) {
|
||||
for (c in text) {
|
||||
when {
|
||||
c == '\t' -> append(" ")
|
||||
unseen(c) -> append("<U+").append(c.code.toString(16).uppercase().padStart(4, '0')).append('>')
|
||||
else -> append(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
// --- A linked device's directories (`GET /api/v2/devices/{id}/directories`) -------------------
|
||||
//
|
||||
// The JSON twin of the page's directory dialog (harness spec 3.9.0), as the contract pins it
|
||||
// (`contract/device_directories*.json`). Every field has a default, so a server that says less
|
||||
// still parses.
|
||||
|
||||
/** The model last used in a directory on the device, as one the person still has. */
|
||||
@Serializable
|
||||
data class DirectoryModel(val id: String = "", val name: String = "", val ref: String = "") {
|
||||
/** What to call it: its name, else its id. */
|
||||
val label: String get() = name.ifBlank { id }
|
||||
}
|
||||
|
||||
/** A subdirectory: whether a session may be opened in it ([reason]: the device's words when not), and its [model]. */
|
||||
@Serializable
|
||||
data class DirectoryEntry(
|
||||
val path: String = "",
|
||||
val name: String = "",
|
||||
val accepted: Boolean = true,
|
||||
val reason: String = "",
|
||||
val model: DirectoryModel? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* One directory on a device, or -- with an empty [path] -- the device's places. Where there is
|
||||
* no listing, [code] says why (`device_not_linked`, `cli_too_old`, `no_answer`, `refused`) and
|
||||
* [error] is the sentence for the person; a typed path still works then.
|
||||
*/
|
||||
@Serializable
|
||||
data class DeviceDirectory(
|
||||
val device: String = "",
|
||||
val path: String = "",
|
||||
val name: String = "",
|
||||
val accepted: Boolean = true,
|
||||
val reason: String = "",
|
||||
val model: DirectoryModel? = null,
|
||||
val parent: String = "",
|
||||
val roots: List<String> = emptyList(),
|
||||
val entries: List<DirectoryEntry> = emptyList(),
|
||||
/** Whether the device says a directory's model at all. */
|
||||
val remembers: Boolean = false,
|
||||
val code: String = "",
|
||||
val error: String = "",
|
||||
) {
|
||||
/** The device's places, not a directory. */
|
||||
val places: Boolean get() = path.isEmpty()
|
||||
|
||||
/** Whether this answer is a listing; one with a [code] is the reason there is none. */
|
||||
val listed: Boolean get() = code.isEmpty()
|
||||
}
|
||||
|
||||
/**
|
||||
* The model a new agent chat on a device and directory starts on when the app names none
|
||||
* (`GET /models?kind=agent&device=&directory=`): [from] `directory` (the model last used
|
||||
* there) or `default`. The device remembers it; nothing here is kept by the app.
|
||||
*/
|
||||
@Serializable
|
||||
data class StartModel(val model: String = "", val from: String = "", val ref: String = "") {
|
||||
/** The model's unambiguous name where the server says one, else its id. */
|
||||
val key: String get() = ref.ifBlank { model }
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import java.text.NumberFormat
|
||||
import java.util.Locale
|
||||
|
||||
/*
|
||||
* One display in every client (harness spec 3.7.0, `display.md`): what this app says about a tool
|
||||
* call, the end of a reply and a number -- the same things, from the same data, as the web UI,
|
||||
* Desktop and the CLI.
|
||||
*/
|
||||
|
||||
/** The states that end a turn without finishing it; their line stays on the reply (`display.end`). */
|
||||
val END_PHASES = setOf("stopped", "failed")
|
||||
|
||||
/**
|
||||
* A call's short title as a line may show it (`display.md` §1, step 4): trimmed, its first line
|
||||
* only, and cut to [max] code points -- one fewer and `…` -- so a cut title says it was cut.
|
||||
* Null when nothing is left.
|
||||
*/
|
||||
fun shortTitle(text: String?, max: Int = TITLE_MAX): String? {
|
||||
val line = text?.trim()?.lineSequence()?.firstOrNull()?.trim().orEmpty()
|
||||
if (line.isEmpty()) return null
|
||||
if (line.codePointCount(0, line.length) <= max) return line
|
||||
return line.substring(0, line.offsetByCodePoints(0, max - 1)) + "…"
|
||||
}
|
||||
|
||||
/** `loop.json` `progress.what_max`. */
|
||||
const val TITLE_MAX = 80
|
||||
|
||||
/**
|
||||
* The state a drawn call is in (`display.md` §2): `running`, `done`, `failed` or `denied`, from
|
||||
* what `/api/v2` says of it.
|
||||
*/
|
||||
fun ToolCall.state(): String = when {
|
||||
// The server's own word, from spec 3.7.0; an older one leaves it to what the call carries.
|
||||
block.state in CALL_STATES -> block.state
|
||||
|
||||
status == "denied" -> "denied"
|
||||
|
||||
status == "error" || !error.isNullOrEmpty() -> "failed"
|
||||
|
||||
status == "running" || status == "pending" -> "running"
|
||||
|
||||
else -> "done"
|
||||
}
|
||||
|
||||
private val CALL_STATES = setOf("running", "done", "failed", "denied")
|
||||
|
||||
/**
|
||||
* What is written after a call's title for its time: the server's own [ToolBlock.duration] where
|
||||
* it sends one (it measured the call), else made from the call's `ms`; nothing for a call that is
|
||||
* running or was denied.
|
||||
*/
|
||||
fun ToolCall.took(): String? {
|
||||
val state = state()
|
||||
if (state == "running" || state == "denied") return null
|
||||
return block.duration.ifBlank { null } ?: callDuration(state, ms)
|
||||
}
|
||||
|
||||
/**
|
||||
* How long a finished call took (`display.md` §2): tenths under a minute (`0.4s`), then
|
||||
* `1m 05s`, then `2h 03m`. None for a call that is running or was denied, or whose time was not
|
||||
* kept. Not a locale number: written with `.` everywhere.
|
||||
*/
|
||||
fun callDuration(state: String, ms: Long?): String? {
|
||||
if (ms == null || state == "running" || state == "denied") return null
|
||||
// Tenths, rounded half up, decide the form: 59.96 s is not "60.0s" but a minute.
|
||||
val tenths = (ms.coerceAtLeast(0) + 50) / 100
|
||||
if (tenths < 600) return "${tenths / 10}.${tenths % 10}s"
|
||||
val seconds = (ms / 1000).coerceAtLeast(60)
|
||||
val minutes = seconds / 60
|
||||
return if (minutes < 60) {
|
||||
String.format(Locale.ROOT, "%dm %02ds", minutes, seconds % 60)
|
||||
} else {
|
||||
String.format(Locale.ROOT, "%dh %02dm", minutes / 60, minutes % 60)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How a reply ended, when it did not finish (`display.md` §4): the `stopped` or `failed` progress
|
||||
* whose line stays on it. From the row's own `end` (spec 3.7.0: the phase and the reason, stored
|
||||
* with the reply); from an older server, the end the stream said (kept on the message as its
|
||||
* `progress`), else what the row knows -- that it was stopped, or its error, of which the first
|
||||
* line is the reason. Null for a reply that
|
||||
* finished, a user's message, or one still queued.
|
||||
*/
|
||||
fun Message.ending(): Progress? = when {
|
||||
role != "assistant" -> null
|
||||
|
||||
// What the server stored with the reply (spec 3.7.0): it stays true after a reload.
|
||||
end?.phase in END_PHASES -> Progress(phase = end?.phase.orEmpty(), reason = end?.reason?.ifBlank { null })
|
||||
|
||||
progress?.phase in END_PHASES -> progress
|
||||
|
||||
!error.isNullOrBlank() -> Progress(phase = "failed", reason = error.lineSequence().firstOrNull { it.isNotBlank() }?.trim())
|
||||
|
||||
stopped -> Progress(phase = "stopped")
|
||||
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* A count a person reads, in [locale]'s own format -- its grouping and its decimal mark
|
||||
* (`display.md` §6): `12,480`, `12 480`, `12.480`. [Locale.ROOT] is the spec's plain format, no
|
||||
* grouping and `.`, which is what its conformance texts are written in.
|
||||
*/
|
||||
fun localeNumber(n: Long, locale: Locale): String = if (locale == Locale.ROOT) n.toString() else NumberFormat.getIntegerInstance(locale).format(n)
|
||||
|
||||
/** A measure with [decimals] places, in [locale]'s format; plain for [Locale.ROOT]. */
|
||||
fun localeNumber(n: Double, decimals: Int, locale: Locale): String {
|
||||
if (locale == Locale.ROOT) return String.format(Locale.ROOT, "%.${decimals}f", n)
|
||||
val format = NumberFormat.getNumberInstance(locale)
|
||||
format.minimumFractionDigits = decimals
|
||||
format.maximumFractionDigits = decimals
|
||||
format.roundingMode = java.math.RoundingMode.HALF_UP
|
||||
return format.format(n)
|
||||
}
|
||||
|
||||
/** How a message is drawn in the transcript. */
|
||||
enum class Drawn {
|
||||
/** The person's own words: their bubble. */
|
||||
Person,
|
||||
|
||||
/** The model's reply. */
|
||||
Reply,
|
||||
|
||||
/** A line the server wrote in the person's place (`machine`): a quiet note, never their bubble. */
|
||||
Note,
|
||||
|
||||
/** Not drawn at all. */
|
||||
Hidden,
|
||||
}
|
||||
|
||||
/**
|
||||
* How [message] is drawn. A `user` row the server wrote itself (`machine`: a schedule's
|
||||
* instruction, the line that opens a report's conversation) is not something the person said,
|
||||
* so it is never their bubble: a quiet note -- and in a report's conversation ([reportChat]) the
|
||||
* [first] such line, which only tells the model what the conversation continues, is left out,
|
||||
* since the report itself is one tap back. A turn the linked computer's harness started
|
||||
* (`origin` `harness`: a job's end, a team member's report) is such a line whatever else the
|
||||
* row says: nobody typed it, here or in a terminal.
|
||||
*/
|
||||
fun drawn(message: Message, first: Boolean, reportChat: Boolean): Drawn = when {
|
||||
!message.isUser -> Drawn.Reply
|
||||
!message.byMachine -> Drawn.Person
|
||||
reportChat && first -> Drawn.Hidden
|
||||
else -> Drawn.Note
|
||||
}
|
||||
|
||||
/** The `origin` of a turn the linked computer's harness started by itself. */
|
||||
const val ORIGIN_HARNESS = "harness"
|
||||
|
||||
/** The `origin` of a message handed to the linked computer whose arrival there was never heard. */
|
||||
const val ORIGIN_UNSURE = "unsure"
|
||||
|
||||
/**
|
||||
* Whether this is the person's message of which nobody knows whether it reached the linked
|
||||
* computer (`origin` `unsure`, waiting): the instance never sends it by itself, so it is not
|
||||
* "queued, two ahead" -- it says what it is, in the instance's sentence. Any other origin this
|
||||
* app does not know is drawn as none.
|
||||
*/
|
||||
val Message.fateUnknown: Boolean get() = isUser && queued && origin == ORIGIN_UNSURE
|
||||
|
||||
/** The `origin` of a message the linked computer has said it holds for its next turn. */
|
||||
const val ORIGIN_CARRIED = "carried"
|
||||
|
||||
/** Why a message of the person's has not been given to a model yet. */
|
||||
enum class Waiting {
|
||||
/** A reply was being written when it was sent: it goes when its turn comes. */
|
||||
Queued,
|
||||
|
||||
/** Handed to the linked computer, its arrival never heard: the instance never sends it by itself. */
|
||||
Unsure,
|
||||
|
||||
/** The linked computer holds it and takes it in with its next turn. */
|
||||
Carried,
|
||||
}
|
||||
|
||||
/**
|
||||
* How this message waits, or null for one that does not: a message of the person's with
|
||||
* `queued` true. Such a message is not a turn yet, so it is sent now or discarded, never
|
||||
* edited. An origin this app does not know waits as a plain queued one does.
|
||||
*/
|
||||
val Message.waiting: Waiting?
|
||||
get() = when {
|
||||
!isUser || !queued -> null
|
||||
origin == ORIGIN_UNSURE -> Waiting.Unsure
|
||||
origin == ORIGIN_CARRIED -> Waiting.Carried
|
||||
else -> Waiting.Queued
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Edit is offered on this message of the person's: not while a reply is being
|
||||
* [writing], and never on one that still waits -- the instance refuses that, since it has not
|
||||
* been a turn yet and a linked computer may still hold its old words.
|
||||
*/
|
||||
fun Message.editable(writing: Boolean): Boolean = isUser && !writing && !queued
|
||||
|
||||
/** Whether nobody typed this row: the server wrote it (`machine`), or a device's harness did. */
|
||||
val Message.byMachine: Boolean get() = machine || origin == ORIGIN_HARNESS
|
||||
|
||||
/**
|
||||
* Whether [reply] is a finished reply that holds nothing at all and answers a turn nobody typed
|
||||
* ([asked], the row before it): what was said to that turn was never written into the chat
|
||||
* (instances from before the reply to a harness turn followed the device hold a few). One quiet
|
||||
* line says so in its place -- the server's rule for its own page, never a blank row with
|
||||
* buttons. A reply still being written, one that was stopped or failed, one that holds a plan
|
||||
* and nothing else, and an empty reply to something a person asked are not this.
|
||||
*
|
||||
* [live] is the reply this screen knows is being written, by its id: that one is never this,
|
||||
* whatever its row says. A row says `complete` only when the server does, and a row that says
|
||||
* nothing reads as complete ([Message.complete]); the rule does not rest on that alone.
|
||||
*/
|
||||
fun replyUnrecorded(reply: Message, asked: Message?, live: String? = null): Boolean = !reply.isUser &&
|
||||
reply.id != live &&
|
||||
reply.complete &&
|
||||
!reply.stopped &&
|
||||
reply.error.isNullOrBlank() &&
|
||||
reply.end == null &&
|
||||
reply.text.isNullOrBlank() &&
|
||||
reply.steps.isEmpty() &&
|
||||
reply.plan == null &&
|
||||
reply.attachments.isEmpty() &&
|
||||
asked != null &&
|
||||
asked.isUser &&
|
||||
asked.byMachine
|
||||
|
||||
/** The replies of [messages] that are [replyUnrecorded], by id; [live] is the one being written, if any. */
|
||||
fun unrecordedReplies(messages: List<Message>, live: String? = null): Set<String> = messages.indices
|
||||
.filter { replyUnrecorded(messages[it], messages.getOrNull(it - 1), live) }
|
||||
.mapTo(HashSet()) { messages[it].id }
|
||||
@@ -0,0 +1,55 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.flow.onStart
|
||||
import kotlinx.coroutines.flow.onSubscription
|
||||
import kotlinx.coroutines.flow.shareIn
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* One connection to a person's events route (`GET /events`) for everything that watches it --
|
||||
* the drawer's Reports badge, the Scheduled list -- instead of one each. It is open while
|
||||
* somebody watches and closed when nobody does.
|
||||
*
|
||||
* A frame of the route is a whole state (`schedules`, `reports`), which the server sends at
|
||||
* once to a new connection. A watcher that joins a connection already open missed that, so it
|
||||
* is first told the last frame of each such kind this connection carried.
|
||||
*
|
||||
* `reply` is the exception ([MOMENTS]): something that happened, not how things are. It is
|
||||
* passed on to whoever is watching and never said again -- a watcher that joins later would
|
||||
* take a reply long finished for one that has just started.
|
||||
*
|
||||
* A route that refuses (an older server) ends quietly: its watchers hear nothing, as they did
|
||||
* when each asked for itself.
|
||||
*/
|
||||
class EventsHub(private val scope: CoroutineScope) {
|
||||
private class Line(val key: String, val frames: SharedFlow<Frame>, val latest: MutableMap<String, Frame>)
|
||||
|
||||
private var line: Line? = null
|
||||
|
||||
/** The frames of the route [key] names (an instance's id), opened by [open] when nobody watches it yet. */
|
||||
@Synchronized
|
||||
fun frames(key: String, open: () -> Flow<Frame>): Flow<Frame> {
|
||||
val now = line?.takeIf { it.key == key } ?: run {
|
||||
val latest = ConcurrentHashMap<String, Frame>()
|
||||
val shared = open()
|
||||
// A connection opened anew is told everything again: what the last one said is stale.
|
||||
.onStart { latest.clear() }
|
||||
.onEach { if (it.event !in MOMENTS) latest[it.event] = it }
|
||||
.catch { }
|
||||
.shareIn(scope, SharingStarted.WhileSubscribed(), replay = 0)
|
||||
Line(key, shared, latest).also { line = it }
|
||||
}
|
||||
return now.frames.onSubscription { now.latest.values.toList().forEach { emit(it) } }
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** The frames that say something happened, rather than how things are: never told again to a late watcher. */
|
||||
val MOMENTS = setOf("reply")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import java.io.IOException
|
||||
|
||||
// The person's files as a file manager needs them: the shapes of the trash, the versions and a
|
||||
// batch (`contract/files_*.json`, `file_versions.json`, `file_save_conflict.json`), and what the
|
||||
// app decides from a file's kind without a phone: which viewer, a table's rows, a notebook's cells.
|
||||
|
||||
/** One thing in the trash: restored or removed for good by its [id]. */
|
||||
@Serializable
|
||||
data class TrashItem(
|
||||
val id: String = "",
|
||||
val name: String = "",
|
||||
val path: String = "",
|
||||
val kind: String = "file",
|
||||
val size: Long = 0,
|
||||
@SerialName("trashed_at") val trashedAt: String? = null,
|
||||
)
|
||||
|
||||
/** `GET /files/trash`, and what is left after a restore ([restored]: where it went back to) or a removal. */
|
||||
@Serializable
|
||||
data class TrashList(val items: List<TrashItem> = emptyList(), val restored: String? = null, val removed: Int = 0)
|
||||
|
||||
/** One version of a file, newest first in [FileVersions]; [current] is what the file holds now. */
|
||||
@Serializable
|
||||
data class FileVersion(
|
||||
val id: String = "",
|
||||
val sha: String = "",
|
||||
val size: Long = 0,
|
||||
val at: String? = null,
|
||||
val by: String? = null,
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
val current: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class FileVersions(val path: String = "", val sha: String = "", val versions: List<FileVersion> = emptyList())
|
||||
|
||||
/** One path of a batch: done ([ok], and where it is now) or refused, in the server's sentence. */
|
||||
@Serializable
|
||||
data class BatchResult(val path: String = "", val ok: Boolean = false, val to: String? = null, val error: String? = null)
|
||||
|
||||
/** `POST /files/batch`: never all-or-nothing, so [failed] is read even from a 200. */
|
||||
@Serializable
|
||||
data class BatchAnswer(val op: String = "", val to: String? = null, val results: List<BatchResult> = emptyList(), val done: Int = 0, val failed: Int = 0) {
|
||||
/** The server's sentences for what was refused, each once, at most [most]. */
|
||||
fun refusals(most: Int = 3): List<String> = results.filter { !it.ok }.mapNotNull { it.error?.ifBlank { null } }.distinct().take(most)
|
||||
}
|
||||
|
||||
/**
|
||||
* A save the server refused because the file changed since it was opened (409, `conflict: true`):
|
||||
* its sentence, and the [sha] the file holds now. Nothing was written.
|
||||
*/
|
||||
class SaveConflict(message: String, val sha: String) : IOException(message)
|
||||
|
||||
/** The viewer a file gets, by the server's word for what it is. */
|
||||
enum class FileView {
|
||||
/** Markdown, code, text, and the source of an HTML page or an SVG: drawn as text, editable. */
|
||||
Text,
|
||||
Image,
|
||||
Pdf,
|
||||
Audio,
|
||||
Video,
|
||||
Table,
|
||||
Notebook,
|
||||
|
||||
/** Nothing to draw here: what the file is, and Download, Open with, Share. */
|
||||
Details,
|
||||
}
|
||||
|
||||
object FileKinds {
|
||||
/** The kinds whose text the server hands over and the app may save back. */
|
||||
val TEXT = setOf("markdown", "code", "text", "html", "svg")
|
||||
|
||||
/**
|
||||
* The viewer for a file of [kind]. A server that does not say the kind (null) is read as
|
||||
* before: as text, and the content answer says when it is not. An SVG is its source -- the
|
||||
* app has no WebView and draws nothing a file could script.
|
||||
*/
|
||||
fun viewer(kind: String?): FileView = when (kind) {
|
||||
null, "", in TEXT -> FileView.Text
|
||||
"image" -> FileView.Image
|
||||
"pdf" -> FileView.Pdf
|
||||
"audio" -> FileView.Audio
|
||||
"video" -> FileView.Video
|
||||
"table" -> FileView.Table
|
||||
"notebook" -> FileView.Notebook
|
||||
else -> FileView.Details
|
||||
}
|
||||
|
||||
/** Whether the app offers to edit it: a text kind (a table too, as its text) the person may change. */
|
||||
fun editable(kind: String?, writable: Boolean?, withheld: Boolean): Boolean = writable == true && !withheld && (kind in TEXT || kind == "table")
|
||||
|
||||
/** Why [name] cannot be a file's or a folder's name, as the server would refuse it; false for a good one. */
|
||||
fun badName(name: String): Boolean = name.isBlank() || "/" in name || name.trim() in setOf(".", "..")
|
||||
|
||||
/** [name] inside the directory [dir]. */
|
||||
fun child(dir: String, name: String): String = dir.trimEnd('/') + "/" + name.trim()
|
||||
|
||||
/** The directory a path is in; `/` for a path at the top. */
|
||||
fun parent(path: String): String = path.trimEnd('/').substringBeforeLast('/', "").ifEmpty { "/" }
|
||||
|
||||
/** The last name of a path. */
|
||||
fun name(path: String): String = path.trimEnd('/').substringAfterLast('/').ifBlank { path }
|
||||
|
||||
/**
|
||||
* A name another app or a file system may be given: no separators, no control characters,
|
||||
* never empty, and at most [most] bytes as UTF-8 -- a file system counts a name in bytes
|
||||
* (255 of them), and a name in another script is three bytes a letter. A longer name loses
|
||||
* the end of its stem and keeps its extension, which is what says how to open it.
|
||||
*/
|
||||
fun safeName(name: String, most: Int = NAME_MAX_BYTES): String {
|
||||
val kept = name.map { if (it == '/' || it == '\\' || it.isISOControl()) '_' else it }.joinToString("").trim().trim('.').ifBlank { "file" }
|
||||
if (utf8(kept) <= most) return kept
|
||||
val dot = kept.lastIndexOf('.')
|
||||
// An extension is short; a last dot far from the end is a sentence's, and the name is cut as a whole.
|
||||
val ext = if (dot > 0 && utf8(kept.substring(dot)) <= minOf(EXTENSION_MAX_BYTES, most / 2)) kept.substring(dot) else ""
|
||||
val stem = kept.substring(0, kept.length - ext.length)
|
||||
val room = most - utf8(ext)
|
||||
val cut = StringBuilder()
|
||||
var used = 0
|
||||
var i = 0
|
||||
while (i < stem.length) {
|
||||
// By code point: half of a pair is not a character.
|
||||
val point = stem.codePointAt(i)
|
||||
val bytes = utf8(String(Character.toChars(point)))
|
||||
if (used + bytes > room) break
|
||||
cut.appendCodePoint(point)
|
||||
used += bytes
|
||||
i += Character.charCount(point)
|
||||
}
|
||||
return cut.toString().trimEnd().trimEnd('.').ifBlank { "file" } + ext
|
||||
}
|
||||
|
||||
private fun utf8(text: String): Int = text.toByteArray(Charsets.UTF_8).size
|
||||
|
||||
/** The longest name [safeName] gives, in bytes. */
|
||||
const val NAME_MAX_BYTES = 200
|
||||
private const val EXTENSION_MAX_BYTES = 24
|
||||
}
|
||||
|
||||
/** One thing an archive holds: its [name] is the archive's own text (a path inside it), [size] null for a folder and where the archive does not say. */
|
||||
@Serializable
|
||||
data class ArchiveEntry(val name: String = "", val size: Long? = null, val dir: Boolean = false)
|
||||
|
||||
/**
|
||||
* What is inside an archive, listed by the instance and never unpacked: at most 2000 [entries];
|
||||
* [total] how many it holds where it says; [truncated] when there are more than are listed.
|
||||
* [problem] is null, or why there is no listing (`unreadable`, `unsupported`, `busy`), with the
|
||||
* instance's sentence for it in [message].
|
||||
*/
|
||||
@Serializable
|
||||
data class ArchiveListing(
|
||||
val entries: List<ArchiveEntry> = emptyList(),
|
||||
val total: Int? = null,
|
||||
val truncated: Boolean = false,
|
||||
val problem: String? = null,
|
||||
val message: String = "",
|
||||
)
|
||||
|
||||
/**
|
||||
* Where a file known by its id is now (`GET /files/node?id=`): [parent] is the directory to
|
||||
* list, [path] the file. [trashed]: it is in the trash, and [path] is where it lay.
|
||||
*/
|
||||
@Serializable
|
||||
data class FileNode(
|
||||
val id: String = "",
|
||||
val path: String = "",
|
||||
val name: String = "",
|
||||
val parent: String = "",
|
||||
val kind: String = "",
|
||||
@SerialName("file_kind") val fileKind: String? = null,
|
||||
val trashed: Boolean = false,
|
||||
)
|
||||
|
||||
/** Where "Open in Files" leads for a file a chat names by its id. */
|
||||
sealed interface Whereabouts {
|
||||
/** The directory to open: where the file is now. */
|
||||
data class Folder(val path: String) : Whereabouts
|
||||
|
||||
/** It is in the trash: no directory holds it. */
|
||||
data object Trashed : Whereabouts
|
||||
}
|
||||
|
||||
/**
|
||||
* Where to go for a file last known at [written], from what the instance says of its node
|
||||
* ([node]; null from an instance that cannot say): the directory it is in now -- it may have
|
||||
* been renamed or moved -- else the one it was written to.
|
||||
*/
|
||||
fun whereabouts(node: FileNode?, written: String): Whereabouts = when {
|
||||
node == null -> Whereabouts.Folder(FileKinds.parent(written))
|
||||
node.trashed -> Whereabouts.Trashed
|
||||
else -> Whereabouts.Folder(node.parent.ifBlank { FileKinds.parent(node.path.ifBlank { written }) })
|
||||
}
|
||||
|
||||
/** A table's first rows and columns; [cut] when the file has more than is laid out. */
|
||||
data class Table(val rows: List<List<String>>, val columns: Int, val cut: Boolean)
|
||||
|
||||
/**
|
||||
* A CSV or TSV file as rows of cells: quoted cells, doubled quotes and line breaks inside quotes
|
||||
* as RFC 4180 has them. At most [maxRows] rows of at most [maxColumns] cells are kept, each cell
|
||||
* at most [maxCell] characters -- a table is for looking at, the text has all of it. [partial]:
|
||||
* the text is only the file's beginning, so its last line may be half a row and is left out.
|
||||
*/
|
||||
fun parseTable(text: String, delimiter: Char, maxRows: Int = 500, maxColumns: Int = 40, maxCell: Int = 200, partial: Boolean = false): Table {
|
||||
val rows = mutableListOf<List<String>>()
|
||||
var row = mutableListOf<String>()
|
||||
val cell = StringBuilder()
|
||||
var quoted = false
|
||||
var cut = partial
|
||||
var widest = 0
|
||||
var i = 0
|
||||
|
||||
fun endCell() {
|
||||
if (row.size < maxColumns) row += cell.toString().take(maxCell) else cut = true
|
||||
cell.setLength(0)
|
||||
}
|
||||
|
||||
fun endRow(): Boolean {
|
||||
endCell()
|
||||
if (row.size > 1 || row[0].isNotEmpty()) {
|
||||
rows += row
|
||||
widest = maxOf(widest, row.size)
|
||||
}
|
||||
row = mutableListOf()
|
||||
return rows.size < maxRows
|
||||
}
|
||||
|
||||
var open = true
|
||||
while (i < text.length) {
|
||||
val c = text[i]
|
||||
when {
|
||||
quoted && c == '"' && i + 1 < text.length && text[i + 1] == '"' -> {
|
||||
cell.append('"')
|
||||
i++
|
||||
}
|
||||
|
||||
c == '"' && (quoted || cell.isEmpty()) -> quoted = !quoted
|
||||
|
||||
!quoted && c == delimiter -> endCell()
|
||||
|
||||
!quoted && (c == '\n' || c == '\r') -> {
|
||||
if (c == '\r' && i + 1 < text.length && text[i + 1] == '\n') i++
|
||||
if (!endRow()) {
|
||||
cut = cut || i + 1 < text.length
|
||||
open = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
else -> if (cell.length <= maxCell) cell.append(c)
|
||||
}
|
||||
i++
|
||||
}
|
||||
// What is left after the last line break: a whole last row, unless the text was cut short.
|
||||
if (open && !partial && (cell.isNotEmpty() || row.isNotEmpty())) endRow()
|
||||
return Table(rows, widest, cut)
|
||||
}
|
||||
|
||||
/** The delimiter a table file is cut by: a tab for `.tsv` (or a first line with tabs and no commas), else a comma. */
|
||||
fun tableDelimiter(name: String, text: String): Char {
|
||||
if (name.endsWith(".tsv", ignoreCase = true) || name.endsWith(".tab", ignoreCase = true)) return '\t'
|
||||
val first = text.lineSequence().firstOrNull().orEmpty()
|
||||
return if ('\t' in first && ',' !in first) {
|
||||
'\t'
|
||||
} else if (';' in first && ',' !in first) {
|
||||
';'
|
||||
} else {
|
||||
','
|
||||
}
|
||||
}
|
||||
|
||||
/** One cell of a notebook, as text: its [source], and what it printed ([output], plain text only). */
|
||||
data class NotebookCell(val kind: String, val source: String, val output: String = "", val count: Int? = null, val cut: Boolean = false)
|
||||
|
||||
/** A notebook's first cells; [more]: how many are not shown. Null from [parseNotebook]: not a notebook. */
|
||||
data class Notebook(val cells: List<NotebookCell>, val more: Int = 0, val language: String = "")
|
||||
|
||||
/**
|
||||
* A Jupyter notebook, read-only, as text and nothing else: a cell's source, and of its outputs
|
||||
* only the plain text (a stream, `text/plain`, an error's name and value). HTML, pictures and
|
||||
* scripts in an output are not drawn and not kept. Null for a file that is not a notebook.
|
||||
*/
|
||||
fun parseNotebook(text: String, maxCells: Int = 200, maxChars: Int = 20_000): Notebook? {
|
||||
val root = runCatching { LembasJson.parseToJsonElement(text) as? JsonObject }.getOrNull() ?: return null
|
||||
val cells = root["cells"] as? JsonArray ?: return null
|
||||
|
||||
fun words(of: JsonElement?): String = when (of) {
|
||||
is JsonPrimitive -> if (of.isString) of.content else ""
|
||||
is JsonArray -> of.joinToString("") { (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content.orEmpty() }
|
||||
else -> ""
|
||||
}
|
||||
|
||||
fun printed(cell: JsonObject): String = (cell["outputs"] as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }.joinToString("") { out ->
|
||||
when ((out["output_type"] as? JsonPrimitive)?.content) {
|
||||
"stream" -> words(out["text"])
|
||||
"error" -> listOf(words(out["ename"]), words(out["evalue"])).filter { it.isNotBlank() }.joinToString(": ") + "\n"
|
||||
else -> words((out["data"] as? JsonObject)?.get("text/plain")).let { if (it.isEmpty() || it.endsWith("\n")) it else it + "\n" }
|
||||
}
|
||||
}.trimEnd('\n')
|
||||
|
||||
val language = (((root["metadata"] as? JsonObject)?.get("kernelspec") as? JsonObject)?.get("language") as? JsonPrimitive)?.content
|
||||
?: ((((root["metadata"] as? JsonObject)?.get("language_info") as? JsonObject)?.get("name")) as? JsonPrimitive)?.content
|
||||
val read = cells.mapNotNull { it as? JsonObject }.take(maxCells).map { cell ->
|
||||
val source = words(cell["source"])
|
||||
val output = printed(cell)
|
||||
NotebookCell(
|
||||
kind = (cell["cell_type"] as? JsonPrimitive)?.content ?: "code",
|
||||
source = source.take(maxChars),
|
||||
output = output.take(maxChars),
|
||||
count = (cell["execution_count"] as? JsonPrimitive)?.content?.toIntOrNull(),
|
||||
cut = source.length > maxChars || output.length > maxChars,
|
||||
)
|
||||
}
|
||||
return Notebook(read, more = (cells.size - read.size).coerceAtLeast(0), language = language.orEmpty())
|
||||
}
|
||||
|
||||
/**
|
||||
* How much smaller a picture of [width] × [height] is decoded (a power of two, `inSampleSize`):
|
||||
* so its longer edge is at most about [edge] and it holds at most [pixels] pixels, whatever the
|
||||
* file claims. A picture of 30 000 × 30 000 is then a few megabytes in memory, not gigabytes.
|
||||
*/
|
||||
fun sampleFor(width: Int, height: Int, edge: Int = 2560, pixels: Long = 8_000_000): Int {
|
||||
if (width <= 0 || height <= 0) return 1
|
||||
var sample = 1
|
||||
while (maxOf(width, height) / sample > edge || (width.toLong() / sample) * (height.toLong() / sample) > pixels) sample *= 2
|
||||
return sample
|
||||
}
|
||||
|
||||
/**
|
||||
* A file read a piece at a time, for a player that seeks: [fetch] gets the bytes `[from, to]`
|
||||
* (a `Range` request with the token in its header), a few blocks are kept, and a read is
|
||||
* answered from the block its position is in. [length] is the file's size as the server said it.
|
||||
*/
|
||||
class RangeReader(private val length: Long, private val block: Int = BLOCK, private val keep: Int = 6, private val fetch: (from: Long, to: Long) -> ByteArray) {
|
||||
private val blocks = object : LinkedHashMap<Long, ByteArray>(keep, 0.75f, true) {
|
||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, ByteArray>?): Boolean = size > keep
|
||||
}
|
||||
|
||||
/** Up to [size] bytes from [position] into [buffer] at [offset]; -1 at or past the end. */
|
||||
@Synchronized
|
||||
fun read(position: Long, buffer: ByteArray, offset: Int, size: Int): Int {
|
||||
if (position < 0 || position >= length) return -1
|
||||
if (size <= 0) return 0
|
||||
val index = position / block
|
||||
val start = index * block
|
||||
val bytes = blocks[index] ?: fetch(start, minOf(start + block, length) - 1).also { blocks[index] = it }
|
||||
val within = (position - start).toInt()
|
||||
if (within >= bytes.size) return -1
|
||||
val n = minOf(size, bytes.size - within)
|
||||
System.arraycopy(bytes, within, buffer, offset, n)
|
||||
return n
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun close() = blocks.clear()
|
||||
|
||||
companion object {
|
||||
const val BLOCK = 512 * 1024
|
||||
}
|
||||
}
|
||||
|
||||
/** How much of a file's beginning says what it is. */
|
||||
const val SNIFF_BYTES = 16
|
||||
|
||||
private fun ByteArray.begins(at: Int, vararg bytes: Int): Boolean =
|
||||
size >= at + bytes.size && bytes.indices.all { (this[at + it].toInt() and 0xFF) == bytes[it] }
|
||||
|
||||
private fun ByteArray.says(at: Int, word: String): Boolean = size >= at + word.length && word.indices.all { this[at + it].toInt() == word[it].code }
|
||||
|
||||
/**
|
||||
* What a file is by its first bytes ([head], [SNIFF_BYTES] of them are enough), for the kinds a
|
||||
* chat hands out: pictures, sound, video, a PDF, a 3D model, the archives. Null for anything
|
||||
* else -- text has no mark, and a guess is worse than none.
|
||||
*/
|
||||
fun sniffType(head: ByteArray): String? = when {
|
||||
head.begins(0, 0x89, 0x50, 0x4E, 0x47) -> "image/png"
|
||||
head.begins(0, 0xFF, 0xD8, 0xFF) -> "image/jpeg"
|
||||
head.says(0, "GIF8") -> "image/gif"
|
||||
head.says(0, "RIFF") && head.says(8, "WEBP") -> "image/webp"
|
||||
head.says(0, "RIFF") && head.says(8, "WAVE") -> "audio/wav"
|
||||
head.says(0, "BM") -> "image/bmp"
|
||||
head.says(0, "%PDF-") -> "application/pdf"
|
||||
head.says(0, "OggS") -> "audio/ogg"
|
||||
head.says(0, "fLaC") -> "audio/flac"
|
||||
head.says(0, "ID3") || head.begins(0, 0xFF, 0xFB) || head.begins(0, 0xFF, 0xF3) -> "audio/mpeg"
|
||||
head.says(4, "ftyp") -> "video/mp4"
|
||||
head.begins(0, 0x1A, 0x45, 0xDF, 0xA3) -> "video/webm"
|
||||
head.says(0, "glTF") -> "model/gltf-binary"
|
||||
head.says(0, "PK\u0003\u0004") -> "application/zip"
|
||||
head.begins(0, 0x1F, 0x8B) -> "application/gzip"
|
||||
head.says(0, "7z") && head.begins(2, 0xBC, 0xAF) -> "application/x-7z-compressed"
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* The type a copy is offered to another app as ("Open with"): what its bytes say, else what its
|
||||
* name's extension says ([named], the platform's table), else anything. A zip is the one mark
|
||||
* that many kinds of document carry inside, so there a known extension is the better word. The
|
||||
* type the instance said is not asked: it is not the phone's own reading.
|
||||
*/
|
||||
fun openType(head: ByteArray, named: String?): String {
|
||||
val sniffed = sniffType(head)
|
||||
val byName = named?.ifBlank { null }
|
||||
return when {
|
||||
sniffed == null -> byName ?: "*/*"
|
||||
sniffed == "application/zip" && byName != null -> byName
|
||||
else -> sniffed
|
||||
}
|
||||
}
|
||||
@@ -17,15 +17,23 @@ data class LiveReply(
|
||||
val status: String = "",
|
||||
/** The structured progress beside [status] (spec 3.4.0); null from an older server, or idle. */
|
||||
val progress: Progress? = null,
|
||||
/** How the turn ended when it did not finish: the last `stopped` or `failed` progress, with its reason. */
|
||||
val end: Progress? = null,
|
||||
val cards: List<Card> = emptyList(),
|
||||
val jobs: List<Job> = emptyList(),
|
||||
/** The subagent tree (spec 3.4.0), from the `tree` frame; null until there is one. */
|
||||
val tree: SubagentTree? = null,
|
||||
val metrics: Metrics? = null,
|
||||
val steered: Set<String> = emptySet(),
|
||||
/** Set by `done`: the finished row, which replaces this in the transcript. */
|
||||
/**
|
||||
* Set by `done`: the finished row, which replaces this in the transcript. `done` is the end
|
||||
* of the reply -- the stream may stay open after it for one `title` frame, which nobody
|
||||
* waits for.
|
||||
*/
|
||||
val finished: Message? = null,
|
||||
val title: String? = null,
|
||||
/** From `done`: a model is still naming the chat, so [title] is the one made from the prompt. */
|
||||
val titlePending: Boolean = false,
|
||||
/** A queued prompt the server started when this reply ended: the next stream to follow. */
|
||||
val next: String? = null,
|
||||
val closed: Boolean = false,
|
||||
@@ -49,7 +57,9 @@ data class LiveReply(
|
||||
|
||||
"plan" -> copy(plan = decodePlan(data))
|
||||
|
||||
"status" -> decode(StatusFrame.serializer(), data)?.let { copy(status = it.text, progress = it.progress) } ?: this
|
||||
"status" -> decode(StatusFrame.serializer(), data)?.let { frame ->
|
||||
copy(status = frame.text, progress = frame.progress, end = frame.progress?.takeIf { it.phase in END_PHASES })
|
||||
} ?: this
|
||||
|
||||
"ask" -> decode(AskFrame.serializer(), data)?.let { copy(cards = it.cards) } ?: this
|
||||
|
||||
@@ -59,10 +69,26 @@ data class LiveReply(
|
||||
|
||||
"metrics" -> decode(Metrics.serializer(), data)?.let { copy(metrics = it) } ?: this
|
||||
|
||||
"done" -> decode(DoneFrame.serializer(), data)?.let {
|
||||
copy(finished = it.message, title = it.chat.title.ifEmpty { null }, next = it.next, cards = emptyList(), status = "", progress = null)
|
||||
"done" -> decode(DoneFrame.serializer(), data)?.let { done ->
|
||||
// The finished row says that it was stopped or failed; the stream said why (by you,
|
||||
// the step limit, the budget). The reason goes with the row, where its line stays
|
||||
// (display.md §4).
|
||||
val row = done.message
|
||||
val ended = row.stopped || !row.error.isNullOrBlank()
|
||||
copy(
|
||||
finished = if (ended && row.progress == null && end != null) row.copy(progress = end) else row,
|
||||
title = done.chat.title.ifEmpty { null },
|
||||
titlePending = done.chat.titlePending,
|
||||
next = done.next,
|
||||
cards = emptyList(),
|
||||
status = "",
|
||||
progress = null,
|
||||
)
|
||||
} ?: this
|
||||
|
||||
// After `done`, when a model has named the chat: the name, and nothing else changes.
|
||||
"title" -> decode(TitleFrame.serializer(), data)?.let { named -> copy(title = named.chat.title.ifEmpty { title }, titlePending = false) } ?: this
|
||||
|
||||
"close" -> copy(closed = true)
|
||||
|
||||
else -> this
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
// What a model made, as the app is told of it (`contract/tool_media.json`, `media_job*.json`,
|
||||
// `mcp_servers.json`): a tool call's typed result, a long generation's job, and -- because they
|
||||
// arrived with the same server -- the instance's MCP servers and how each is signed in to.
|
||||
|
||||
/**
|
||||
* A file a tool call made: [kind] is what was asked for (`image`, `image_edit`, `video`, `music`,
|
||||
* `model3d`), and the file is in the person's Files at [path] -- a moment's truth, since they may
|
||||
* move it; [nodeId] names it wherever it is. Its bytes are `GET /files/raw?node=`. [width],
|
||||
* [height] and [seconds] are 0 where the server did not know them.
|
||||
*
|
||||
* With [shown] it is a file an agent put in front of the person (`contract/tool_media_shown.json`)
|
||||
* and [kind] is what the file is, read from its bytes: `image`, `audio`, `video`, `pdf`,
|
||||
* `model3d`, `archive`, `binary`, `text`, or a word this app does not know yet. Whatever it is,
|
||||
* its card names it and leads to the file; what the phone can draw is drawn as well.
|
||||
*/
|
||||
@Serializable
|
||||
data class GeneratedMedia(
|
||||
val kind: String = "",
|
||||
val path: String = "",
|
||||
@SerialName("node_id") val nodeId: String = "",
|
||||
@SerialName("version_id") val versionId: String = "",
|
||||
val name: String = "",
|
||||
val mime: String = "",
|
||||
val size: Long = 0,
|
||||
val width: Int = 0,
|
||||
val height: Int = 0,
|
||||
val seconds: Double = 0.0,
|
||||
/** An agent showed this file (the `show` tool on a file that is not text); it did not make it. */
|
||||
val shown: Boolean = false,
|
||||
) {
|
||||
/** How the card shows it, by its kind: an unknown kind is its details, never a player. */
|
||||
val view: MediaView
|
||||
get() = when (kind) {
|
||||
"image", "image_edit" -> MediaView.Picture
|
||||
"video" -> MediaView.Video
|
||||
"music", "audio" -> MediaView.Sound
|
||||
"pdf" -> MediaView.Document
|
||||
else -> MediaView.Details
|
||||
}
|
||||
|
||||
/** The kinds this app has a word for; anything else is said as "File" when shown, never as nothing. */
|
||||
val knownKind: Boolean get() = kind in KINDS
|
||||
|
||||
/** What to call it: its name, else the last name of its path. */
|
||||
val title: String get() = name.ifBlank { FileKinds.name(path) }
|
||||
|
||||
/** Where its bytes are asked for: by its id, which outlives a rename or a move; by its path from a result without one. */
|
||||
val raw: Raw get() = if (nodeId.isNotBlank()) Raw.Node(nodeId) else Raw.Path(path)
|
||||
|
||||
/** The folder of the person's Files it was written to. */
|
||||
val folder: String get() = FileKinds.parent(path)
|
||||
|
||||
companion object {
|
||||
val KINDS = setOf("image", "image_edit", "video", "music", "audio", "model3d", "pdf", "archive", "binary", "text")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a file's card is: a picture drawn, a player, a document with pages the phone can lay out
|
||||
* (a PDF), or -- a 3D model, an archive, anything unknown -- the file's details. Every one of
|
||||
* them names the file and has the ways to it.
|
||||
*/
|
||||
enum class MediaView { Picture, Video, Sound, Document, Details }
|
||||
|
||||
/** The job a tool call started (`media_job`): [state] as it was when the call returned. */
|
||||
@Serializable
|
||||
data class MediaJobRef(val id: String = "", val kind: String = "", val state: String = "")
|
||||
|
||||
/** What a finished job was counted as; an empty [currency] is the instance's own. */
|
||||
@Serializable
|
||||
data class MediaCost(val amount: Double = 0.0, val currency: String = "")
|
||||
|
||||
/**
|
||||
* A long generation (`GET /media/jobs/{id}`): `queued` and `running` are under way, `done` has
|
||||
* its [result], `failed`, `cancelled` and `expired` say why in [error] -- the server's sentence,
|
||||
* for the person. [seconds] is how long it has taken so far, or took. [told]: the chat was woken
|
||||
* with a reply about it.
|
||||
*/
|
||||
@Serializable
|
||||
data class MediaJob(
|
||||
val id: String = "",
|
||||
val kind: String = "",
|
||||
val state: String = "",
|
||||
val active: Boolean = false,
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
@SerialName("message_id") val messageId: String? = null,
|
||||
val source: String = "",
|
||||
val prompt: String = "",
|
||||
val started: String? = null,
|
||||
val ended: String? = null,
|
||||
val deadline: String? = null,
|
||||
val seconds: Double = 0.0,
|
||||
val error: String = "",
|
||||
val result: GeneratedMedia? = null,
|
||||
val cost: MediaCost? = null,
|
||||
val told: Boolean = false,
|
||||
) {
|
||||
/** Still to end: by the server's word, or by a state that is one of the two that are under way. */
|
||||
val underWay: Boolean get() = active || state in ACTIVE
|
||||
|
||||
/** Ended some way other than with a file. */
|
||||
val unsuccessful: Boolean get() = !underWay && state != DONE
|
||||
|
||||
companion object {
|
||||
val ACTIVE = setOf("queued", "running")
|
||||
const val DONE = "done"
|
||||
const val CANCELLED = "cancelled"
|
||||
|
||||
/** A job known only by the call that started it. */
|
||||
fun of(ref: MediaJobRef): MediaJob = MediaJob(id = ref.id, kind = ref.kind, state = ref.state, active = ref.state in ACTIVE)
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class MediaJobList(val jobs: List<MediaJob> = emptyList())
|
||||
|
||||
/**
|
||||
* A new file that was not made because something is already called that (409, `exists: true`):
|
||||
* the server's sentence. Nothing was written.
|
||||
*/
|
||||
class FileExists(message: String) : java.io.IOException(message)
|
||||
|
||||
/**
|
||||
* How an MCP server is signed in to: [kind] `none`, `secret` or `oauth`; [state] `ready`,
|
||||
* `signed_in`, `signed_out` or `needs_signin`. [account] is who the provider says signed in -- a
|
||||
* stranger's text, drawn as plain text. [signinUrl] is a page of the instance to open in a
|
||||
* browser, where the person signs in to the instance itself with its cookie: the app's token is
|
||||
* never part of it.
|
||||
*/
|
||||
@Serializable
|
||||
data class McpAuth(
|
||||
val kind: String = "none",
|
||||
val state: String = "ready",
|
||||
val shared: Boolean = false,
|
||||
val account: String = "",
|
||||
@SerialName("expires_at") val expiresAt: String? = null,
|
||||
val renews: Boolean = false,
|
||||
@SerialName("signin_url") val signinUrl: String? = null,
|
||||
) {
|
||||
/** The server's tools are not offered until somebody signs in. */
|
||||
val needsSignIn: Boolean get() = state == "signed_out" || state == "needs_signin"
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class McpServer(val id: String = "", val slug: String = "", val name: String = "", val tools: Int = 0, val auth: McpAuth = McpAuth()) {
|
||||
val label: String get() = name.ifBlank { slug.ifBlank { id } }
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class McpServerList(val servers: List<McpServer> = emptyList())
|
||||
|
||||
/**
|
||||
* The address the browser is sent to for a sign-in: always a page of the instance the app is
|
||||
* signed in to ([base]). An address on that origin is taken as it is; a path alone, or an
|
||||
* address the instance wrote with another name for itself, is that path on [base] -- so nothing
|
||||
* the list says can send the person to another host. Null for no address, or one that is no
|
||||
* http(s) page.
|
||||
*/
|
||||
fun signInAddress(base: String, url: String?): String? {
|
||||
val said = url?.trim().orEmpty()
|
||||
if (said.isEmpty()) return null
|
||||
val want = runCatching { java.net.URI(said) }.getOrNull() ?: return null
|
||||
val home = runCatching { java.net.URI(base) }.getOrNull() ?: return null
|
||||
if (want.scheme != null && want.scheme.lowercase() !in setOf("http", "https")) return null
|
||||
val path = want.rawPath.orEmpty()
|
||||
if (!path.startsWith("/") || path.startsWith("//")) return null
|
||||
|
||||
fun port(u: java.net.URI) = when {
|
||||
u.port >= 0 -> u.port
|
||||
u.scheme.equals("https", true) -> 443
|
||||
else -> 80
|
||||
}
|
||||
val same = want.scheme != null && want.scheme.equals(home.scheme, true) && want.host != null && want.host.equals(home.host, true) &&
|
||||
port(want) == port(home) && want.userInfo == null
|
||||
return if (same) said else base.trimEnd('/') + path + want.rawQuery?.let { "?$it" }.orEmpty()
|
||||
}
|
||||
|
||||
/** Which bytes of the instance are asked for: a file of the tree (or one version of it), a file by its id, or a chat's attachment. */
|
||||
sealed interface Raw {
|
||||
data class Path(val path: String, val version: String? = null) : Raw
|
||||
|
||||
/** A file by its node id, wherever it is now: what a generated file's result carries. */
|
||||
data class Node(val id: String) : Raw
|
||||
|
||||
/** A chat's attachment. Answered whole: a player gets a copy, not a stream. */
|
||||
data class Attached(val id: String) : Raw
|
||||
}
|
||||
@@ -117,7 +117,29 @@ data class ModelInfo(
|
||||
val default: Boolean = false,
|
||||
/** Whether a new chat on this model is offered subagents (server 2.0.0-beta.7); null from an older one. */
|
||||
val subagents: SubagentsOffer? = null,
|
||||
/** On a connection whose terms allow interactive use only: never a schedule's model. */
|
||||
@SerialName("interactive_only") val interactiveOnly: Boolean = false,
|
||||
/**
|
||||
* The model's one unambiguous name, `provider/id` (server 2.0.0-beta.14): two connections may
|
||||
* serve one [id], which alone names only the first of them. Empty from an older server.
|
||||
*/
|
||||
val ref: String = "",
|
||||
val provider: String = "",
|
||||
/** The connection's name, for telling two models with one [id] apart. */
|
||||
val connection: String = "",
|
||||
/**
|
||||
* What the model is for (server 2.0.0-beta.17): `chat`, or a word for something a chat cannot
|
||||
* start on (`embedding`, and later `image`, `video`, …). A server that does not say it offers
|
||||
* only models to chat with.
|
||||
*/
|
||||
val capability: String = CHAT,
|
||||
) {
|
||||
/** Whether a chat can be on it: the one capability this app's pickers offer. An unknown word is not one. */
|
||||
val forChat: Boolean get() = capability == CHAT
|
||||
|
||||
/** What this model is chosen, kept and sent by: its [ref], or its [id] from a server without refs. */
|
||||
val key: String get() = ref.ifBlank { id }
|
||||
|
||||
/**
|
||||
* The levels, for a server that says them; an older one said only `efforts`, offered after
|
||||
* an `off` that meant "the model's default" -- as the app showed it before.
|
||||
@@ -149,9 +171,60 @@ data class ModelInfo(
|
||||
|
||||
companion object {
|
||||
val CONTROLS = setOf("none", "switch", "slider")
|
||||
const val CHAT = "chat"
|
||||
}
|
||||
}
|
||||
|
||||
/** The models a chat can be on, of a list: what every model picker and the assistant's model setting offer. */
|
||||
fun List<ModelInfo>.forChat(): List<ModelInfo> = filter { it.forChat }
|
||||
|
||||
/**
|
||||
* The model a name means, in a list: by its `ref`, else the first with that `id` -- which is
|
||||
* what a bare id names on the server too. So a name kept from before refs (a setting, a chat's
|
||||
* `model`, a schedule's) still finds its model.
|
||||
*/
|
||||
fun List<ModelInfo>.named(name: String?): ModelInfo? {
|
||||
if (name.isNullOrBlank()) return null
|
||||
return firstOrNull { it.ref == name } ?: firstOrNull { it.id == name }
|
||||
}
|
||||
|
||||
/**
|
||||
* The model a kept name means when it is known how the name was said. A name the server said as
|
||||
* a `model_ref` ([isRef]) is looked up as a ref and nothing else: an id may itself hold a slash
|
||||
* (a model of an aggregator, `openai/gpt`), so a ref whose model has left the list could
|
||||
* otherwise "find" another connection's model that happens to be called that. A name of
|
||||
* unknown kind -- a setting, a pick -- goes through [named].
|
||||
*/
|
||||
fun List<ModelInfo>.named(name: String?, isRef: Boolean): ModelInfo? = if (isRef) firstOrNull { !name.isNullOrBlank() && it.ref == name } else named(name)
|
||||
|
||||
/**
|
||||
* The model a chat, a reply or a schedule is on, in a list. The server says the id (`model`) and,
|
||||
* where it knows it, which connection serves it (`model_ref`). With a [ref] the model is the one
|
||||
* with that ref and no other: one that is not in the list is no model here, never "the first
|
||||
* with that id" -- that would name the wrong connection. Without one (an older server, or a
|
||||
* connection that is gone) the bare [id] is all there is.
|
||||
*/
|
||||
fun List<ModelInfo>.serving(ref: String?, id: String?): ModelInfo? = if (ref.isNullOrBlank()) named(id) else firstOrNull { it.ref == ref }
|
||||
|
||||
/** What such a thing's model is kept and sent by: its [ref] where the server says one, else its [id]; null for neither. */
|
||||
fun modelKey(ref: String?, id: String?): String? = ref?.ifBlank { null } ?: id?.ifBlank { null }
|
||||
|
||||
/**
|
||||
* The quiet line under a reply: the model's [id] as before, and its connection only where the
|
||||
* reply says which one ([ref]) and another model here shares the id. Null when there is no id.
|
||||
*/
|
||||
fun List<ModelInfo>.replyModel(ref: String?, id: String?): String? {
|
||||
val said = id?.ifBlank { null } ?: return null
|
||||
val model = firstOrNull { !ref.isNullOrBlank() && it.ref == ref } ?: return said
|
||||
return twinTitle(said, model.connection, count { it.id == model.id } > 1)
|
||||
}
|
||||
|
||||
/** A model's name in a list of [all]: with its connection where another model there shares its id. */
|
||||
fun ModelInfo.titleAmong(all: List<ModelInfo>): String = twinTitle(name.ifBlank { id }, connection, all.count { it.id == id } > 1)
|
||||
|
||||
/** "Name · Connection" for a model one of two that share an id ([twin]), where the connection has a name; else the name. */
|
||||
fun twinTitle(name: String, connection: String, twin: Boolean): String = if (twin && connection.isNotBlank()) "$name · $connection" else name
|
||||
|
||||
@Serializable
|
||||
data class ModelList(
|
||||
val models: List<ModelInfo> = emptyList(),
|
||||
@@ -159,7 +232,12 @@ data class ModelList(
|
||||
@SerialName("subagents_cap") val subagentsCap: Int? = null,
|
||||
/** With `kind=agent` (spec 3.4.0 §14): whether a new agent chat may have subagents. */
|
||||
@SerialName("agent_subagents") val agentSubagents: AgentSubagents? = null,
|
||||
)
|
||||
/** With `kind=agent`, a device and a directory (spec 3.9.0): the model a new agent chat there starts on. */
|
||||
val start: StartModel? = null,
|
||||
) {
|
||||
/** The same answer with only the models a chat can be on. */
|
||||
fun forChat(): ModelList = if (models.all { it.forChat }) this else copy(models = models.forChat())
|
||||
}
|
||||
|
||||
/**
|
||||
* A new agent chat's Subagents fact (`/models?kind=agent&device=`): [offered] where the instance
|
||||
@@ -222,7 +300,34 @@ data class SearchResults(
|
||||
|
||||
/** One app release the server recommends (`GET /api/v2/apps`), with the page its files are on. */
|
||||
@Serializable
|
||||
data class AppRelease(val version: String = "", val tag: String = "", val channel: String = "", val page: String = "")
|
||||
data class AppRelease(
|
||||
val version: String = "",
|
||||
val tag: String = "",
|
||||
val channel: String = "",
|
||||
val page: String = "",
|
||||
/** The release's other builds, for an updater that installs its own kind: `{url, sha256}` each, where the server knows them. */
|
||||
val notifications: AppBuild? = null,
|
||||
val fdroid: AppBuild? = null,
|
||||
)
|
||||
|
||||
/** One APK of a release: where it is and its SHA-256. */
|
||||
@Serializable
|
||||
data class AppBuild(val url: String = "", val sha256: String = "")
|
||||
|
||||
/** What `@` offers from the server (`GET /api/v2/mentions`): an earlier `attachment` by [id], a `file` of the tree by [path], or a `url`. */
|
||||
@Serializable
|
||||
data class Mention(val kind: String = "", val id: String = "", val path: String = "", val url: String = "", val name: String = "", val detail: String = "")
|
||||
|
||||
@Serializable
|
||||
data class Mentions(val items: List<Mention> = emptyList())
|
||||
|
||||
/** A file or directory on a linked device, by its [path] from the chat's directory ([kind] `file` or `dir`). */
|
||||
@Serializable
|
||||
data class DeviceFile(val path: String = "", val kind: String = "", val name: String = "")
|
||||
|
||||
/** What `@` offers in an agent chat (`GET /devices/{id}/files`): the device's files; one that cannot answer offers none and may say why. */
|
||||
@Serializable
|
||||
data class DeviceFiles(val files: List<DeviceFile> = emptyList(), val error: String = "", val device: String = "")
|
||||
|
||||
@Serializable
|
||||
data class ServerChannel(val version: String = "", val channel: String = "")
|
||||
@@ -269,7 +374,27 @@ data class FolderList(val folders: List<Folder> = emptyList())
|
||||
data class Device(@SerialName("token_id") val tokenId: String? = null, val directory: String = "")
|
||||
|
||||
@Serializable
|
||||
data class LinkedDevice(val id: String, val name: String = "", val host: String = "", val platform: String = "")
|
||||
data class LinkedDevice(
|
||||
val id: String,
|
||||
val name: String = "",
|
||||
val host: String = "",
|
||||
val platform: String = "",
|
||||
/** Whether the device accepts scheduled work: only then may an Agentic schedule belong to it. */
|
||||
val scheduled: Boolean = false,
|
||||
/** The widest mode the device lets a scheduled run have; empty where it accepts none. */
|
||||
@SerialName("max_mode") val maxMode: String = "",
|
||||
/** Whether the device remembers the model last used in a directory (spec 3.9.0). */
|
||||
@SerialName("directory_model") val directoryModel: Boolean = false,
|
||||
/** Whether the device hands its files over the link at all (spec 3.11.0, `fs`). Parsed; no screen reads it yet. */
|
||||
val files: Boolean = false,
|
||||
/** False where its highest mode is plan: its files can be read and not changed. */
|
||||
@SerialName("files_writable") val filesWritable: Boolean = false,
|
||||
/** Whether the device lets files that run code (git's own, an agent's configuration) be changed from here. */
|
||||
@SerialName("files_that_run_code") val filesThatRunCode: Boolean = false,
|
||||
) {
|
||||
/** What to call it: its name, else its host. */
|
||||
val label: String get() = name.ifBlank { host.ifBlank { id } }
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class DeviceList(val devices: List<LinkedDevice> = emptyList())
|
||||
@@ -280,6 +405,8 @@ data class Chat(
|
||||
val kind: String = "chat",
|
||||
val title: String = "",
|
||||
val model: String = "",
|
||||
/** Which connection serves [model] (`provider/model`); null from an older server, or when that connection is gone. */
|
||||
@SerialName("model_ref") val modelRef: String? = null,
|
||||
@SerialName("folder_id") val folderId: String? = null,
|
||||
val pinned: Boolean = false,
|
||||
val archived: Boolean = false,
|
||||
@@ -295,6 +422,10 @@ data class Chat(
|
||||
@SerialName("created_at") val createdAt: String? = null,
|
||||
@SerialName("updated_at") val updatedAt: String? = null,
|
||||
@SerialName("system_prompt") val systemPrompt: String? = null,
|
||||
/** What may be done to this chat (`rename`, `delete`, `archive`, `pin`, `folder`); null from a server that does not say: everything. */
|
||||
val controls: List<String>? = null,
|
||||
/** The report this chat continues (`kind` `report`): such a chat lives under Reports, not among the chats. */
|
||||
val report: ChatReport? = null,
|
||||
val plan: JsonObject? = null,
|
||||
/** The team's size: how many agents, its own included, the chat may have. */
|
||||
val agents: AgentsSetting? = null,
|
||||
@@ -302,8 +433,17 @@ data class Chat(
|
||||
val subagents: SubagentsOffer? = null,
|
||||
) {
|
||||
val isAgent: Boolean get() = kind == "agent"
|
||||
|
||||
/** The chat's model as it is looked up and sent: its ref, else its id. */
|
||||
val modelKey: String? get() = modelKey(modelRef, model)
|
||||
|
||||
fun allows(control: String): Boolean = controls?.contains(control) ?: true
|
||||
}
|
||||
|
||||
/** The report a chat continues: its id and title. */
|
||||
@Serializable
|
||||
data class ChatReport(val id: String = "", val title: String = "")
|
||||
|
||||
/** A chat's `agents {min, max}` (harness spec 3.2.0): `1 ≤ min ≤ max ≤` the instance's cap. */
|
||||
@Serializable
|
||||
data class AgentsSetting(val min: Int = 1, val max: Int = 4) {
|
||||
@@ -319,6 +459,16 @@ data class ChatPage(val chats: List<Chat> = emptyList(), val more: Boolean = fal
|
||||
@Serializable
|
||||
data class ChatDetail(val chat: Chat, val messages: List<Message> = emptyList(), val more: Boolean = false, val live: String? = null)
|
||||
|
||||
/**
|
||||
* `GET /events`, frame `reply`: a reply started in the chat [chatId] -- whoever started it, this
|
||||
* app's own too -- and, with [live] false, that it is over (`event_reply_end.json`): once per
|
||||
* reply, however it ended; a reply shorter than the news of its start is said by that one frame
|
||||
* alone. [messageId] is the reply's row. An event, not a state: a start is said once (and, on a
|
||||
* connection just opened, for every reply being written then), an end once and never again.
|
||||
*/
|
||||
@Serializable
|
||||
data class ReplyFrame(@SerialName("chat_id") val chatId: String = "", @SerialName("message_id") val messageId: String = "", val live: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class MessagePage(val messages: List<Message> = emptyList(), val more: Boolean = false)
|
||||
|
||||
@@ -355,8 +505,23 @@ data class Metrics(
|
||||
@SerialName("tok_s") val tokPerSecond: Double = 0.0,
|
||||
)
|
||||
|
||||
/**
|
||||
* How a call is drawn (`display.md`): its [kind], the one short [title], the facts after it as
|
||||
* [chips] (an edit's `+N −M`, a non-zero `exit N`, the hits), and from spec 3.7.0 its [state]
|
||||
* (running, done, failed, denied), the [duration] of a finished call as the spec writes it, and
|
||||
* the tool's name as a person reads it ([label]). The last three are empty from an older server.
|
||||
*/
|
||||
@Serializable
|
||||
data class ToolBlock(val kind: String = "tool", val title: String = "", val chips: List<String> = emptyList(), val added: Int = 0, val removed: Int = 0)
|
||||
data class ToolBlock(
|
||||
val kind: String = "tool",
|
||||
val title: String = "",
|
||||
val chips: List<String> = emptyList(),
|
||||
val added: Int = 0,
|
||||
val removed: Int = 0,
|
||||
val state: String = "",
|
||||
val duration: String = "",
|
||||
val label: String = "",
|
||||
)
|
||||
|
||||
/** One tool call. What the tool wrote varies by tool, so the free-form parts stay JSON. */
|
||||
@Serializable
|
||||
@@ -376,6 +541,8 @@ data class ToolCall(
|
||||
val diff: String? = null,
|
||||
val exit: Int? = null,
|
||||
val hits: Int? = null,
|
||||
/** How long the call took, in milliseconds (spec 3.7.0: `tool_end`'s `ms`); null where it was not kept. */
|
||||
val ms: Long? = null,
|
||||
val path: String? = null,
|
||||
val truncated: Boolean = false,
|
||||
val job: JsonElement? = null,
|
||||
@@ -384,6 +551,10 @@ data class ToolCall(
|
||||
val show: ShowCard? = null,
|
||||
/** `image_generate`'s picture: the server's own attachment, by id, and its size. */
|
||||
val image: GeneratedImage? = null,
|
||||
/** The file the call made (a picture, video, music, a 3D model), which is in the person's Files. */
|
||||
val media: GeneratedMedia? = null,
|
||||
/** A generation that takes minutes: the job the call started, as it was when the call returned. */
|
||||
@SerialName("media_job") val mediaJob: MediaJobRef? = null,
|
||||
val block: ToolBlock = ToolBlock(),
|
||||
)
|
||||
|
||||
@@ -437,6 +608,12 @@ data class FileEntry(
|
||||
val name: String = "",
|
||||
val path: String = "",
|
||||
val kind: String = "file",
|
||||
/**
|
||||
* What the file is, read by the server from its name and its own bytes: `markdown`, `code`,
|
||||
* `text`, `html`, `image`, `svg`, `pdf`, `audio`, `video`, `table`, `notebook`, `model3d`,
|
||||
* `archive` or `binary`. Null for a folder, and from a server that does not say it.
|
||||
*/
|
||||
@SerialName("file_kind") val fileKind: String? = null,
|
||||
val size: Long = 0,
|
||||
val mime: String = "",
|
||||
@SerialName("updated_at") val updatedAt: String? = null,
|
||||
@@ -447,7 +624,13 @@ data class FileEntry(
|
||||
|
||||
/** A directory, through the person's own access. `parent` is null at `/`. */
|
||||
@Serializable
|
||||
data class FileListing(val path: String = "/", val parent: String? = null, val entries: List<FileEntry> = emptyList())
|
||||
data class FileListing(
|
||||
val path: String = "/",
|
||||
val parent: String? = null,
|
||||
val entries: List<FileEntry> = emptyList(),
|
||||
/** After a copy: the new entry, under the name the server gave it (a taken name is numbered). */
|
||||
val copied: FileEntry? = null,
|
||||
)
|
||||
|
||||
/** Why a file's text did not come: `reason` is `not_text` or `too_large`; `message` says it. */
|
||||
@Serializable
|
||||
@@ -464,10 +647,17 @@ data class FileContent(
|
||||
val size: Long = 0,
|
||||
val mime: String = "",
|
||||
val kind: String = "text",
|
||||
/** What the file is ([FileEntry.fileKind]); null from a server that does not say it. */
|
||||
@SerialName("file_kind") val fileKind: String? = null,
|
||||
/** Whether the person may change it; null from a server that does not say (then: no editing). */
|
||||
val writable: Boolean? = null,
|
||||
val language: String = "",
|
||||
/** What the file holds now: sent back as a save's `base`, so a save over somebody else's change is refused. */
|
||||
val sha: String = "",
|
||||
val text: String = "",
|
||||
val withheld: Withheld? = null,
|
||||
/** What is inside an archive, as far as the instance lists it; null for every other kind and from a server that does not say. */
|
||||
val archive: ArchiveListing? = null,
|
||||
) {
|
||||
/** The kind the viewer draws, by the `show` card's rule: anything unknown is plain text. */
|
||||
val viewKind: String get() = if (kind in ShowCard.VIEW_KINDS) kind else "text"
|
||||
@@ -476,7 +666,7 @@ data class FileContent(
|
||||
@Serializable
|
||||
data class SteerNote(val id: String = "", val text: String = "")
|
||||
|
||||
/** One step of a reply: `thinking`, `text`, `tools` or `steer`. */
|
||||
/** One step of a reply: `thinking`, `text`, `tools`, `steer` or `page`. */
|
||||
@Serializable
|
||||
data class Step(
|
||||
val index: Int = 0,
|
||||
@@ -485,10 +675,32 @@ data class Step(
|
||||
val text: String? = null,
|
||||
val label: String? = null,
|
||||
val markdown: String? = null,
|
||||
/** A `page` step's title (spec 3.8.0): the page itself is not sent to a client that does not draw it. */
|
||||
val title: String? = null,
|
||||
/** A `text` step's pages (spec 3.8.0): where it has any, [text] is its markdown with each page as the one line `[page: Title]`. */
|
||||
val pages: List<StepPage> = emptyList(),
|
||||
val calls: List<ToolCall> = emptyList(),
|
||||
val messages: List<SteerNote> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* A reply's end when it did not finish: `stopped` with `person`, `steps`, `budget` or no reason,
|
||||
* or `failed` with the error's first line. [text] is the line in the account's language; the app
|
||||
* writes its own from [phase] and [reason], in the app's language.
|
||||
*/
|
||||
@Serializable
|
||||
data class MessageEnd(val phase: String = "", val reason: String = "", val text: String = "")
|
||||
|
||||
/** A page in a reply's text: its title (the page itself is fetched by its digest, by a client that draws pages). */
|
||||
@Serializable
|
||||
data class StepPage(val title: String = "", val digest: String = "")
|
||||
|
||||
/**
|
||||
* What a client that draws no pages shows of a `text` step: the server's own text where the step
|
||||
* has pages (each page its one line), else the markdown as it is.
|
||||
*/
|
||||
val Step.shownMarkdown: String get() = text?.takeIf { pages.isNotEmpty() && it.isNotBlank() } ?: markdown.orEmpty()
|
||||
|
||||
@Serializable
|
||||
data class Message(
|
||||
val id: String,
|
||||
@@ -497,10 +709,14 @@ data class Message(
|
||||
val complete: Boolean = true,
|
||||
val stopped: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** How a reply that did not finish ended (spec 3.7.0); null for one that finished, or from an older server. */
|
||||
val end: MessageEnd? = null,
|
||||
val queued: Boolean = false,
|
||||
val machine: Boolean = false,
|
||||
val origin: String = "",
|
||||
val model: String? = null,
|
||||
/** Which connection wrote this reply (see [Chat.modelRef]). */
|
||||
@SerialName("model_ref") val modelRef: String? = null,
|
||||
val attachments: List<Attachment> = emptyList(),
|
||||
val text: String? = null,
|
||||
val steps: List<Step> = emptyList(),
|
||||
@@ -515,6 +731,10 @@ data class Message(
|
||||
@Serializable
|
||||
data class Turn(val message: Message? = null, val reply: Message? = null)
|
||||
|
||||
/** The answer to discarding a waiting message: the row that is gone, by its id. */
|
||||
@Serializable
|
||||
data class Discarded(val id: String = "", val discarded: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class NewChat(val chat: Chat, val message: Message? = null, val reply: Message? = null)
|
||||
|
||||
@@ -538,14 +758,53 @@ data class CardItem(
|
||||
val options: List<Option> = emptyList(),
|
||||
val multiple: Boolean = false,
|
||||
@SerialName("free_text") val freeText: Boolean = true,
|
||||
/** An approval: whether "Always allow" is offered beside "Allow once" (spec 3.7.0). An older server says nothing, and offered it always. */
|
||||
val always: Boolean = true,
|
||||
val editable: Boolean = false,
|
||||
val plan: JsonObject? = null,
|
||||
@SerialName("mode_choice") val modeChoice: Boolean = false,
|
||||
val job: String = "",
|
||||
/** The tree subagent asking (spec 3.4.0), for a call nobody in the tree may allow; null otherwise. */
|
||||
val subagent: CardSubagent? = null,
|
||||
/**
|
||||
* A `phone_action` card's action (spec 3.6.0, `phone.md` §2): `action`, `summary` and the
|
||||
* action's own fields, as the server checked them. Carried out by `actions/ActionRunner`.
|
||||
*/
|
||||
val phone: JsonObject? = null,
|
||||
/** An edit's changes, one per file (`contract/event_ask_edit.json`); empty on a card without them. */
|
||||
val diffs: List<FileDiff> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* What an edit would do to one file, on its approval card: [oldText] is null for a file that is
|
||||
* made, [deleted] marks one that goes. Both texts are a model's and a file's words: drawn as
|
||||
* text by the app's own diff view (`api/Diff.kt`), never rendered.
|
||||
*/
|
||||
@Serializable
|
||||
data class FileDiff(
|
||||
val path: String = "",
|
||||
@SerialName("old_text") val oldText: String? = null,
|
||||
@SerialName("new_text") val newText: String = "",
|
||||
val deleted: Boolean = false,
|
||||
) {
|
||||
/** A file that does not exist yet. */
|
||||
val made: Boolean get() = oldText == null && !deleted
|
||||
}
|
||||
|
||||
/**
|
||||
* A person's two models for an editor (`GET /editor`, `contract/editor.json`): parsed so the
|
||||
* shape is pinned; this app has no screen for them.
|
||||
*/
|
||||
@Serializable
|
||||
data class EditorModels(val autocomplete: Autocomplete = Autocomplete(), val main: Main = Main()) {
|
||||
/** [source]: `person`, `instance` or null with no model. [allowed]: the refs an administrator allows, null for any. */
|
||||
@Serializable
|
||||
data class Autocomplete(val model: String? = null, val source: String? = null, val allowed: List<String>? = null)
|
||||
|
||||
@Serializable
|
||||
data class Main(val model: String? = null)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class CardSubagent(val id: String = "", val name: String = "", val position: String = "")
|
||||
|
||||
@@ -582,6 +841,8 @@ data class Job(
|
||||
/** The answer to a card, as the page's form says it (see `api/v2/chats.py:answer`). */
|
||||
@Serializable
|
||||
data class CardAnswer(
|
||||
/** A phone card's answer: what the phone did once the person confirmed or declined. */
|
||||
val result: PhoneResult? = null,
|
||||
val verdict: String = "",
|
||||
val reason: String = "",
|
||||
val choices: Map<String, List<String>> = emptyMap(),
|
||||
@@ -589,12 +850,40 @@ data class CardAnswer(
|
||||
val asks: Map<String, String> = emptyMap(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PhoneResult(val status: String, val message: String = "")
|
||||
|
||||
@Serializable
|
||||
data class PushKey(val key: String = "", val registered: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class Transcript(val text: String = "")
|
||||
|
||||
/**
|
||||
* Which chat a recording or a reading is for: the chat's own id, or -- for a chat that does not
|
||||
* exist yet -- the model it will be on. The instance serves it from that model's connection
|
||||
* where the connection has speech models of its own; with neither ([DEFAULT]) from its default.
|
||||
* Never both: a chat that exists says its model itself.
|
||||
*/
|
||||
data class MediaFor(val chatId: String? = null, val chatModel: String? = null) {
|
||||
companion object {
|
||||
/** No chat: another app's dictation. */
|
||||
val DEFAULT = MediaFor()
|
||||
|
||||
fun of(chatId: String?, model: String?): MediaFor = when {
|
||||
!chatId.isNullOrBlank() -> MediaFor(chatId = chatId)
|
||||
!model.isNullOrBlank() -> MediaFor(chatModel = model)
|
||||
else -> DEFAULT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A recording written down; [fallback] names the source that answered when the chat's own did not. */
|
||||
data class Heard(val text: String, val fallback: String? = null)
|
||||
|
||||
/** Words as sound (mp3); [fallback] as [Heard]'s. */
|
||||
class Spoken(val audio: ByteArray, val fallback: String? = null)
|
||||
|
||||
// --- The stream's frames -----------------------------------------------------------------
|
||||
@Serializable
|
||||
data class Tail(val thinking: String = "", val text: String = "", val label: String = "")
|
||||
@@ -625,10 +914,19 @@ data class JobsFrame(val jobs: List<Job> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class DoneFrame(val message: Message, val chat: DoneChat = DoneChat(), val next: String? = null) {
|
||||
/**
|
||||
* [titlePending]: a model is still naming the chat, so [title] is the one made from the
|
||||
* prompt and a `title` frame may follow before `close`. `done` is the end of the reply all
|
||||
* the same.
|
||||
*/
|
||||
@Serializable
|
||||
data class DoneChat(val id: String = "", val title: String = "")
|
||||
data class DoneChat(val id: String = "", val title: String = "", @SerialName("title_pending") val titlePending: Boolean = false)
|
||||
}
|
||||
|
||||
/** The `title` frame: the name a model gave the chat, after `done`. */
|
||||
@Serializable
|
||||
data class TitleFrame(val chat: DoneFrame.DoneChat = DoneFrame.DoneChat())
|
||||
|
||||
/** The push payload the server sends (services/push.py), as the app reads it. */
|
||||
@Serializable
|
||||
data class PushPayload(
|
||||
@@ -648,6 +946,10 @@ data class PushPayload(
|
||||
*/
|
||||
@SerialName("schedule_id") val scheduleId: String? = null,
|
||||
@SerialName("run_id") val runId: String? = null,
|
||||
/** A report was filed (`kind` `report`, spec 3.8.0): its id; [title] and [body] are its title and summary, [url] `/reports/{id}`. */
|
||||
@SerialName("report_id") val reportId: String? = null,
|
||||
/** A report's `normal` or `high`. */
|
||||
val importance: String? = null,
|
||||
val status: String? = null,
|
||||
val visibility: String? = null,
|
||||
val actions: List<String> = emptyList(),
|
||||
|
||||
@@ -36,7 +36,7 @@ data class Progress(
|
||||
) {
|
||||
companion object {
|
||||
/** `loop.json` `progress.no_elapsed`: drawn as their text alone. */
|
||||
val NO_ELAPSED = setOf("stopped", "failed")
|
||||
val NO_ELAPSED = END_PHASES
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,14 +51,16 @@ fun interface ProgressWords {
|
||||
}
|
||||
|
||||
/**
|
||||
* The phase's text, its fields filled (`progress.md` §2): numbers as integers, a rate with one
|
||||
* decimal in [locale]'s format, `retrying`'s `in` counted down to [now]. Null for a phase this
|
||||
* app does not know -- a newer server's -- so the caller falls back to the `status` text.
|
||||
* The phase's text, its fields filled (`progress.md` §2): every count and measure in [locale]'s
|
||||
* own number format (`display.md` §6: the phone's grouping and decimal mark; [Locale.ROOT] is the
|
||||
* spec's plain format), a title that had to be cut ending in `…`, `retrying`'s `in` counted down
|
||||
* to [now]. Null for a phase this app does not know -- a newer server's -- so the caller falls
|
||||
* back to the `status` text.
|
||||
*/
|
||||
fun progressText(progress: Progress, words: ProgressWords, now: Long, locale: Locale = Locale.getDefault()): String? {
|
||||
val p = progress
|
||||
return when (p.phase) {
|
||||
"queued" -> if (p.ahead != null) words.text("queued_ahead", "${p.ahead}") else words.text("queued")
|
||||
"queued" -> if (p.ahead != null) words.text("queued_ahead", localeNumber(p.ahead.toLong(), locale)) else words.text("queued")
|
||||
|
||||
"waiting_for_model" -> {
|
||||
val model = p.model ?: return null
|
||||
@@ -72,7 +74,8 @@ fun progressText(progress: Progress, words: ProgressWords, now: Long, locale: Lo
|
||||
val done = p.done
|
||||
val total = p.total
|
||||
if (done != null && total != null && total > 0) {
|
||||
words.text("reading_prompt", "$done", "$total", "${done.toLong() * 100 / total}")
|
||||
val percent = localeNumber(done.toLong() * 100 / total, locale)
|
||||
words.text("reading_prompt", localeNumber(done.toLong(), locale), localeNumber(total.toLong(), locale), percent)
|
||||
} else {
|
||||
words.text("reading_prompt_bare")
|
||||
}
|
||||
@@ -80,11 +83,13 @@ fun progressText(progress: Progress, words: ProgressWords, now: Long, locale: Lo
|
||||
|
||||
"thinking" -> words.text("thinking")
|
||||
|
||||
"writing" -> p.rate?.let { words.text("writing", String.format(locale, "%.1f", it)) } ?: words.text("writing_bare")
|
||||
"writing" -> p.rate?.let { words.text("writing", localeNumber(it, 1, locale)) } ?: words.text("writing_bare")
|
||||
|
||||
"running_tool" -> {
|
||||
val tool = p.tool ?: return null
|
||||
if (!p.what.isNullOrBlank()) words.text("running_tool", tool, p.what.take(80)) else words.text("running_tool_bare", tool)
|
||||
// The call's short title (display.md §1): one line, and `…` where it had to be cut.
|
||||
val what = shortTitle(p.what)
|
||||
if (what != null) words.text("running_tool", tool, what) else words.text("running_tool_bare", tool)
|
||||
}
|
||||
|
||||
"waiting_for_person" -> {
|
||||
@@ -96,7 +101,7 @@ fun progressText(progress: Progress, words: ProgressWords, now: Long, locale: Lo
|
||||
words.text("waiting_for_person", what)
|
||||
}
|
||||
|
||||
"waiting_for_subagents" -> words.text("waiting_for_subagents", "${p.running ?: 0}")
|
||||
"waiting_for_subagents" -> words.text("waiting_for_subagents", localeNumber((p.running ?: 0).toLong(), locale))
|
||||
|
||||
"compacting" -> words.text("compacting")
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.ExperimentalSerializationApi
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonNames
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
|
||||
// --- Reports (`/api/v2/reports`, harness spec 3.8.0 `reports.md`) -----------------------------
|
||||
//
|
||||
// A schedule's run does not answer into a chat: it files a report, or it does not. The server
|
||||
// stores the reports and lists them; a report's body is Markdown, as a reply is.
|
||||
//
|
||||
// The shapes are read leniently where an id may come as a string or as an object carrying one
|
||||
// ([chat], a run's `report`), so that a server that says a little more still parses; the
|
||||
// contract fixtures (`contract/report*.json`) pin what it says.
|
||||
|
||||
/** The schedule a report came from: its id and its name. */
|
||||
@Serializable
|
||||
data class ReportSchedule(val id: String = "", val title: String = "")
|
||||
|
||||
/**
|
||||
* One report: [title] a headline, [summary] a sentence or two for a list or a notification,
|
||||
* [importance] `normal` or `high` (look now), the [schedule] that filed it, [created] when, and
|
||||
* whether it is still [unread]. Read alone it also carries its [body] (Markdown a model wrote:
|
||||
* untrusted) and the [chat] a reply continues in, once there is one.
|
||||
*/
|
||||
@OptIn(ExperimentalSerializationApi::class)
|
||||
@Serializable
|
||||
data class Report(
|
||||
val id: String,
|
||||
val title: String = "",
|
||||
val summary: String = "",
|
||||
val importance: String = "normal",
|
||||
val schedule: ReportSchedule? = null,
|
||||
/** The schedule's name as it was when the report was filed: what is left once the schedule itself is gone. */
|
||||
@SerialName("schedule_title") val scheduleTitle: String = "",
|
||||
@JsonNames("created_at") val created: String? = null,
|
||||
val unread: Boolean = false,
|
||||
val body: String? = null,
|
||||
/** The body as text: every page in it replaced by its one line, `[page: Title]`; the body itself where it has none. */
|
||||
val text: String? = null,
|
||||
/** The pages the body has: only these are pages -- an `html-view` fence the server does not list is a code block. */
|
||||
val pages: List<StepPage> = emptyList(),
|
||||
val model: String? = null,
|
||||
val chat: JsonElement? = null,
|
||||
) {
|
||||
val high: Boolean get() = importance == "high"
|
||||
|
||||
/** The name of the task it came from: the schedule's as it is now, else as it was. */
|
||||
val from: String get() = schedule?.title?.ifBlank { null } ?: scheduleTitle
|
||||
|
||||
/** The chat a reply to this report continues in; null before the first reply. */
|
||||
val chatId: String? get() = idOf(chat)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class ReportList(val reports: List<Report> = emptyList(), val unread: Int? = null) {
|
||||
/** How many reports are unread: the server's count, else as many as it listed unread. */
|
||||
val unreadCount: Int get() = unread ?: reports.count { it.unread }
|
||||
}
|
||||
|
||||
/** `GET /events`, frame `reports`: the count of the unread, and the newest report. */
|
||||
@Serializable
|
||||
data class ReportsFrame(val unread: Int = 0, val newest: Report? = null, @SerialName("latest_created") val latestCreated: String? = null)
|
||||
|
||||
/** `POST /reports/{id}/reply`: the chat the conversation about the report is in. */
|
||||
@Serializable
|
||||
data class ReportReply(val chat: JsonElement? = null) {
|
||||
val chatId: String? get() = idOf(chat)
|
||||
}
|
||||
|
||||
/** An id that came as a string, or as an object with an `id`; null for anything else. */
|
||||
internal fun idOf(element: JsonElement?): String? = when (element) {
|
||||
is JsonPrimitive -> element.contentOrNull?.takeIf { element.isString && it.isNotBlank() }
|
||||
is JsonObject -> idOf(element["id"])
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** Reports as the list shows them: the unread first, then the newest first within each half. */
|
||||
fun sortedReports(reports: List<Report>): List<Report> = reports.sortedWith(compareByDescending<Report> { it.unread }.thenByDescending { it.created.orEmpty() })
|
||||
|
||||
/**
|
||||
* When a schedule's owner wants to hear from it (`loop.json` `scheduled.notify`): `always` (a
|
||||
* report every run), `when` (only when the person's own words hold) or `never` (history only).
|
||||
* A server before 3.8.0 said `matters` for what is now `when`; anything else is the default.
|
||||
*/
|
||||
fun notifyChoice(notify: String): String = when (notify) {
|
||||
"always", "never" -> notify
|
||||
else -> "when"
|
||||
}
|
||||
|
||||
/**
|
||||
* An id as the server makes them -- letters, digits, `_` and `-`, at most 64 -- or null. Anything
|
||||
* that came from outside the app (a push payload, an intent's extra) is passed through this
|
||||
* before it becomes part of a route or an address: a `/` in it must not open another page.
|
||||
*/
|
||||
fun safeId(id: String?): String? = id?.takeIf { SAFE_ID.matches(it) }
|
||||
|
||||
private val SAFE_ID = Regex("^[A-Za-z0-9_-]{1,64}$")
|
||||
@@ -2,6 +2,7 @@ package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
|
||||
// --- Scheduled tasks (`/api/v2/schedules`) ------------------------------------------------
|
||||
@@ -10,13 +11,20 @@ import kotlinx.serialization.json.JsonObject
|
||||
// `event_schedules.json`; `ContractTest` reads every one). Every field has a default, so a
|
||||
// server that says less still parses.
|
||||
|
||||
/** The model a run used: [reason] `switched` when it stood in for [switchedFrom], which was busy. */
|
||||
/**
|
||||
* The model a run used, and how it came to it ([reason]): `pinned` (the schedule's own),
|
||||
* `switched` (it stood in for [switchedFrom], which was busy), `directory` (the folder's usual
|
||||
* model, asked of the computer), `default` (the person's default, where the folder had none) or
|
||||
* `session` (a continued conversation kept its own).
|
||||
*/
|
||||
@Serializable
|
||||
data class RunModel(
|
||||
val id: String? = null,
|
||||
val name: String? = null,
|
||||
val reason: String? = null,
|
||||
@SerialName("switched_from") val switchedFrom: String? = null,
|
||||
/** Which connection served the run (`provider/model`); null from an older server. */
|
||||
val ref: String? = null,
|
||||
) {
|
||||
/** What to call it: its name, else its id. */
|
||||
val label: String? get() = name ?: id
|
||||
@@ -28,9 +36,13 @@ data class RunTokens(val prompt: Long = 0, val completion: Long = 0)
|
||||
@Serializable
|
||||
data class RunCost(val micro: Long = 0, val currency: String = "")
|
||||
|
||||
/** Why a run failed or waits: [kind] a class the app may read, [text] the server's own sentence. */
|
||||
/**
|
||||
* Why a run failed or waits: [kind] a class the app may read, [text] the sentence to show (the
|
||||
* server's, or the device's own), and [reason] a narrower word where there is one -- `terminal`:
|
||||
* the schedule's session was open in a terminal on the computer.
|
||||
*/
|
||||
@Serializable
|
||||
data class RunError(@SerialName("class") val kind: String = "", val text: String = "")
|
||||
data class RunError(@SerialName("class") val kind: String = "", val text: String = "", val reason: String? = null)
|
||||
|
||||
/**
|
||||
* One run of a schedule: when it was due and how it went. [status] is `running`, `waiting` (no
|
||||
@@ -67,13 +79,22 @@ data class ScheduleRun(
|
||||
val notification: RunNotification? = null,
|
||||
/** A watching schedule's look at its address on this run (`unchanged` when nothing moved). */
|
||||
val watch: RunWatch? = null,
|
||||
)
|
||||
/** The run's line in the history (spec 3.8.0): the answer's first line, or why no report was filed. */
|
||||
val note: String = "",
|
||||
/** The report this run filed, when it filed one: its id (or an object carrying it). */
|
||||
val report: JsonElement? = null,
|
||||
/** Where an Agentic schedule's run ran (spec 3.9.0); null for a Chat schedule's, or from an older server. */
|
||||
@SerialName("ran_on") val ranOn: RanOn? = null,
|
||||
) {
|
||||
val reportId: String? get() = idOf(report)
|
||||
}
|
||||
|
||||
/**
|
||||
* A scheduled task. [description] is the rule in words, as the server says it ("On the second
|
||||
* Monday of each month at 07:30"), in [timezone]; [rule] the server's own form of it; [request]
|
||||
* the person's words it was made from; [instruction] what the model is asked each time.
|
||||
* [notify] is `always`, `matters` or `never`; [mode] `fresh` (a chat per run) or `continue`.
|
||||
* [notify] is `always`, `when` or `never` (spec 3.8.0; `matters` before it) and [notifyWhen] the
|
||||
* person's own words for `when`; [mode] `fresh` (a chat per run) or `continue`.
|
||||
*/
|
||||
@Serializable
|
||||
data class Schedule(
|
||||
@@ -90,9 +111,14 @@ data class Schedule(
|
||||
val target: String = "chat",
|
||||
val mode: String = "",
|
||||
val notify: String = "",
|
||||
@SerialName("notify_when") val notifyWhen: String = "",
|
||||
/** What "When…" means while [notifyWhen] is empty, in the account's language. */
|
||||
@SerialName("notify_default") val notifyDefault: String = "",
|
||||
@SerialName("catch_up") val catchUp: String = "",
|
||||
@SerialName("grace_minutes") val graceMinutes: Int? = null,
|
||||
val model: String? = null,
|
||||
/** Which connection serves [model] (`provider/model`); null from an older server, or with no model of its own. */
|
||||
@SerialName("model_ref") val modelRef: String? = null,
|
||||
val effort: String? = null,
|
||||
val agents: Int? = null,
|
||||
val tools: List<String> = emptyList(),
|
||||
@@ -110,6 +136,9 @@ data class Schedule(
|
||||
@SerialName("created_at") val createdAt: String? = null,
|
||||
) {
|
||||
val paused: Boolean get() = !enabled
|
||||
|
||||
/** The schedule's model as a form holds and sends it: its ref, else its id. */
|
||||
val modelKey: String? get() = modelKey(modelRef, model)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
@@ -174,15 +203,55 @@ data class SchedulingModel(
|
||||
val free: Boolean = false,
|
||||
val busy: String? = null,
|
||||
val chosen: Boolean = true,
|
||||
)
|
||||
/** The model's unambiguous name (`provider/id`) and its connection's, as on every model object. */
|
||||
val ref: String = "",
|
||||
val connection: String = "",
|
||||
) {
|
||||
/** What a schedule's model is chosen and sent by: its [ref], or its [id] from a server without refs. */
|
||||
val key: String get() = ref.ifBlank { id }
|
||||
}
|
||||
|
||||
/** The scheduling model a name means: by its `ref`, else the first with that `id`. */
|
||||
fun List<SchedulingModel>.named(name: String?): SchedulingModel? {
|
||||
if (name.isNullOrBlank()) return null
|
||||
return firstOrNull { it.ref == name } ?: firstOrNull { it.id == name }
|
||||
}
|
||||
|
||||
/** The same when it is known that the server said the name as a `model_ref` ([isRef]): then by ref alone, never by an id that looks like it. */
|
||||
fun List<SchedulingModel>.named(name: String?, isRef: Boolean): SchedulingModel? =
|
||||
if (isRef) firstOrNull { !name.isNullOrBlank() && it.ref == name } else named(name)
|
||||
|
||||
/**
|
||||
* What a schedule's or a run's model is called among [this] list: [said] (the id or the name
|
||||
* the server gave), and its connection where the server says which one ([ref]) and another
|
||||
* model in the list shares the id. A ref the list does not have leaves [said] as it is.
|
||||
*/
|
||||
fun List<SchedulingModel>.saidWithConnection(ref: String?, said: String?): String? {
|
||||
val word = said?.ifBlank { null } ?: return null
|
||||
val model = firstOrNull { !ref.isNullOrBlank() && it.ref == ref } ?: return word
|
||||
return twinTitle(word, model.connection, count { it.id == model.id } > 1)
|
||||
}
|
||||
|
||||
/** A scheduling model's name in a list of [all]: with its connection where another there shares its id. */
|
||||
fun SchedulingModel.titleAmong(all: List<SchedulingModel>): String = twinTitle(name.ifBlank { id }, connection, all.count { it.id == id } > 1)
|
||||
|
||||
/** `GET`/`PUT /schedules/models`: the models, the instance's order, and the person's narrowing. */
|
||||
@Serializable
|
||||
data class SchedulingModels(val models: List<SchedulingModel> = emptyList(), val instance: List<String> = emptyList(), val mine: List<String> = emptyList())
|
||||
|
||||
/** What a watching schedule looks at before each run: [kind] `url` and the address. */
|
||||
/**
|
||||
* What a watching schedule looks at before each run: [kind] `url` and the address, or -- on a
|
||||
* linked computer -- `command`, the [command] run in the schedule's folder and how many seconds
|
||||
* it may take ([timeoutS]). [target] is either, as one string.
|
||||
*/
|
||||
@Serializable
|
||||
data class ScheduleWatch(val kind: String = "", val target: String = "", @SerialName("changed_at") val changedAt: String? = null)
|
||||
data class ScheduleWatch(
|
||||
val kind: String = "",
|
||||
val target: String = "",
|
||||
val command: String = "",
|
||||
@SerialName("timeout_s") val timeoutS: Int? = null,
|
||||
@SerialName("changed_at") val changedAt: String? = null,
|
||||
)
|
||||
|
||||
/** One run's look: whether the address [changed] since the last one, or why the look failed. */
|
||||
@Serializable
|
||||
@@ -206,6 +275,8 @@ data class RunNotification(
|
||||
val actions: List<String> = emptyList(),
|
||||
val labels: Map<String, String> = emptyMap(),
|
||||
val ask: String = "",
|
||||
/** A report's notification: `normal` or `high`. */
|
||||
val importance: String = "",
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -222,5 +293,31 @@ data class RunsOn(
|
||||
@SerialName("approval_wait_minutes") val approvalWaitMinutes: Int? = null,
|
||||
)
|
||||
|
||||
/** Where one run ran: the computer ([deviceName]), the folder there and the mode it had. */
|
||||
@Serializable
|
||||
data class RanOn(val device: String = "", @SerialName("device_name") val deviceName: String = "", val cwd: String = "", val mode: String = "")
|
||||
|
||||
/** The two types of schedule (spec 3.9.0). There is no field for it: Agentic is one with a computer. */
|
||||
val Schedule.agentic: Boolean get() = runsOn != null
|
||||
|
||||
/** A run that waits because its computer is not linked (`error.class` `device_away`). */
|
||||
val ScheduleRun.computerAway: Boolean get() = error?.kind == "device_away"
|
||||
|
||||
/**
|
||||
* What a save says about where a schedule runs, which is its type: nothing ([Leave]), on the
|
||||
* server ([Server]: Chat), or on a computer ([Computer]: Agentic) -- in a folder there, in a
|
||||
* mode, with an approval's wait in minutes (null: the server's default).
|
||||
*/
|
||||
sealed interface WhereToRun {
|
||||
data object Leave : WhereToRun
|
||||
|
||||
data object Server : WhereToRun
|
||||
|
||||
data class Computer(val device: String, val cwd: String, val mode: String, val approvalWaitMinutes: Int?) : WhereToRun
|
||||
}
|
||||
|
||||
/**
|
||||
* The command an Agentic schedule watches before each run, as a save says it: the [command]
|
||||
* (empty: watch nothing) and how many seconds it may take (null: the server's own).
|
||||
*/
|
||||
data class WatchCommand(val command: String, val timeoutS: Int?)
|
||||
@@ -22,52 +22,39 @@ data class Frame(val event: String, val data: String)
|
||||
* what [LiveReply.apply] wants.
|
||||
*
|
||||
* A refusal (a 4xx: the chat was deleted, the token signed out) ends the flow with the error;
|
||||
* only a broken connection is retried.
|
||||
* only a broken connection is retried -- and each opening after the first is a new request, so
|
||||
* it waits for its `turn` (the gate: nothing new is asked behind a lock).
|
||||
*/
|
||||
class StreamClient(private val api: ApiClient) {
|
||||
private val http = api.http.newBuilder().readTimeout(0, TimeUnit.SECONDS).build()
|
||||
|
||||
fun follow(chatId: String, messageId: String): Flow<Frame> = flow {
|
||||
var wait = 1_000L
|
||||
while (true) {
|
||||
var closed = false
|
||||
var refused: ApiException? = null
|
||||
once(api.streamRequest(chatId, messageId)).collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
wait = 1_000L
|
||||
emit(result.frame)
|
||||
if (result.frame.event == "close") closed = true
|
||||
}
|
||||
|
||||
is Outcome.Refused -> refused = result.error
|
||||
|
||||
is Outcome.Dropped -> Unit
|
||||
}
|
||||
}
|
||||
refused?.let { throw it }
|
||||
if (closed) return@flow
|
||||
delay(wait)
|
||||
wait = (wait * 2).coerceAtMost(30_000L)
|
||||
}
|
||||
}
|
||||
fun follow(chatId: String, messageId: String, turn: suspend () -> Unit = {}): Flow<Frame> = reopened(turn) { once(api.streamRequest(chatId, messageId)) }
|
||||
|
||||
/**
|
||||
* Follow an events route that ends itself now and then (`close` after a while, as the
|
||||
* activity panel's does): opened again at once after a `close`, and after a pause that
|
||||
* grows to 30 seconds when the connection drops. It runs until its collector stops; a
|
||||
* refusal (4xx) ends it with the error.
|
||||
* grows to 30 seconds when the connection drops or closes without a frame. It runs until
|
||||
* its collector stops; a refusal (4xx) ends it with the error. Each opening, the first
|
||||
* too, waits for its [turn].
|
||||
*/
|
||||
fun watch(request: () -> Request): Flow<Frame> = flow {
|
||||
fun watch(turn: suspend () -> Unit = {}, request: () -> Request): Flow<Frame> = flow {
|
||||
var wait = 1_000L
|
||||
while (true) {
|
||||
var closed = false
|
||||
var said = false
|
||||
var refused: ApiException? = null
|
||||
// Every opening is a request of its own: it waits for its turn (the gate).
|
||||
turn()
|
||||
once(request()).collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
wait = 1_000L
|
||||
if (result.frame.event == "close") closed = true else emit(result.frame)
|
||||
if (result.frame.event == "close") {
|
||||
closed = true
|
||||
} else {
|
||||
said = true
|
||||
wait = 1_000L
|
||||
emit(result.frame)
|
||||
}
|
||||
}
|
||||
|
||||
is Outcome.Refused -> refused = result.error
|
||||
@@ -76,18 +63,15 @@ class StreamClient(private val api: ApiClient) {
|
||||
}
|
||||
}
|
||||
refused?.let { throw it }
|
||||
if (closed) continue
|
||||
// A route that closes after it has said something is opened again at once. One
|
||||
// that closes having said nothing waits as a dropped one does: a server that only
|
||||
// ever answers `close` must not be asked in a tight loop.
|
||||
if (reopenAtOnce(closed, said)) continue
|
||||
delay(wait)
|
||||
wait = (wait * 2).coerceAtMost(30_000L)
|
||||
}
|
||||
}
|
||||
|
||||
private sealed interface Outcome {
|
||||
data class Event(val frame: Frame) : Outcome
|
||||
data class Refused(val error: ApiException) : Outcome
|
||||
data object Dropped : Outcome
|
||||
}
|
||||
|
||||
private fun once(request: Request): Flow<Outcome> = callbackFlow {
|
||||
val source = EventSources.createFactory(http).newEventSource(
|
||||
request,
|
||||
@@ -115,3 +99,45 @@ class StreamClient(private val api: ApiClient) {
|
||||
awaitClose { source.cancel() }
|
||||
}
|
||||
}
|
||||
|
||||
/** What one opening of a stream gave: a frame, a refusal (4xx), or a connection that broke. */
|
||||
sealed interface Outcome {
|
||||
data class Event(val frame: Frame) : Outcome
|
||||
data class Refused(val error: ApiException) : Outcome
|
||||
data object Dropped : Outcome
|
||||
}
|
||||
|
||||
/**
|
||||
* A reply's stream, [open]ed again whenever it ends before `close`: after a pause of 1, 2, 4, 8 …
|
||||
* up to 30 seconds, and after its [turn] -- every opening but the first is a request nobody is
|
||||
* waiting for at that moment, so it asks first whether it may start. A refusal ends the flow
|
||||
* with the error.
|
||||
*/
|
||||
fun reopened(turn: suspend () -> Unit, open: () -> Flow<Outcome>): Flow<Frame> = flow {
|
||||
var wait = 1_000L
|
||||
while (true) {
|
||||
var closed = false
|
||||
var refused: ApiException? = null
|
||||
open().collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
wait = 1_000L
|
||||
emit(result.frame)
|
||||
if (result.frame.event == "close") closed = true
|
||||
}
|
||||
|
||||
is Outcome.Refused -> refused = result.error
|
||||
|
||||
is Outcome.Dropped -> Unit
|
||||
}
|
||||
}
|
||||
refused?.let { throw it }
|
||||
if (closed) return@flow
|
||||
delay(wait)
|
||||
wait = (wait * 2).coerceAtMost(30_000L)
|
||||
turn()
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether an events route that ended is opened again without a pause: only one that [closed] itself after it [said] something. */
|
||||
fun reopenAtOnce(closed: Boolean, said: Boolean): Boolean = closed && said
|
||||
@@ -3,17 +3,36 @@ package eu.llembas.android.assist
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.service.quicksettings.Tile
|
||||
import android.service.quicksettings.TileService
|
||||
import eu.llembas.android.R
|
||||
|
||||
/** A Quick Settings tile that opens the assistant's sheet: one more way in besides the power button. */
|
||||
/**
|
||||
* A Quick Settings tile that opens the assistant's sheet: one more way in besides the power
|
||||
* button. It is a button, not a switch -- always shown as ready (`STATE_INACTIVE`), never as
|
||||
* "on", and the system's default (`STATE_UNAVAILABLE` on some phones until the first update)
|
||||
* would grey it out. Over the lock screen the sheet opens there and asks to unlock before it
|
||||
* sends anything, as from any other way in.
|
||||
*/
|
||||
class AskTileService : TileService() {
|
||||
override fun onStartListening() {
|
||||
super.onStartListening()
|
||||
qsTile?.apply {
|
||||
state = Tile.STATE_INACTIVE
|
||||
label = getString(R.string.tile_ask)
|
||||
updateTile()
|
||||
}
|
||||
}
|
||||
|
||||
@android.annotation.SuppressLint("StartActivityAndCollapseDeprecated")
|
||||
override fun onClick() {
|
||||
super.onClick()
|
||||
val intent = Intent(this, AssistActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
if (Build.VERSION.SDK_INT >= 34) {
|
||||
// Android 14 refuses the Intent overload; the PendingIntent one is the way now.
|
||||
startActivityAndCollapse(PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE))
|
||||
startActivityAndCollapse(
|
||||
PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
startActivityAndCollapse(intent)
|
||||
|
||||
@@ -2,8 +2,14 @@ package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.app.NotificationManager
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
@@ -11,11 +17,78 @@ import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.wake.AssistLink
|
||||
import eu.llembas.android.wake.AssistPresence
|
||||
import eu.llembas.android.wake.WakeWordService
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import java.lang.ref.WeakReference
|
||||
|
||||
/** What a way into the sheet asks for. */
|
||||
enum class Opening {
|
||||
Sheet,
|
||||
Listen,
|
||||
Continue,
|
||||
;
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* A headset's voice button sends `VOICE_COMMAND` (or, locked, `VOICE_SEARCH_HANDS_FREE`):
|
||||
* the person means to speak, so the sheet opens listening whatever Settings says. Those
|
||||
* two are Android's, and anybody's to send. The app's own ways in -- listening for the
|
||||
* widget's microphone and the wake word, the last chat -- count only on an intent the
|
||||
* app made itself ([own], [OwnIntents]); from anyone else they are just the sheet.
|
||||
*/
|
||||
fun of(action: String?, listenExtra: Boolean, own: Boolean): Opening = when {
|
||||
own && listenExtra -> Listen
|
||||
own && action == AssistActivity.ACTION_CONTINUE -> Continue
|
||||
own && action == AssistActivity.ACTION_LISTEN -> Listen
|
||||
action in PUBLIC_LISTENING -> Listen
|
||||
else -> Sheet
|
||||
}
|
||||
|
||||
fun of(intent: Intent, own: Boolean): Opening = of(intent.action, own && intent.getBooleanExtra(AssistActivity.EXTRA_LISTEN, false), own)
|
||||
|
||||
private val PUBLIC_LISTENING = setOf(Intent.ACTION_VOICE_COMMAND, "android.speech.action.VOICE_SEARCH_HANDS_FREE")
|
||||
}
|
||||
}
|
||||
|
||||
/** How the sheet starts, given whether the phone is locked. */
|
||||
enum class LockedStart {
|
||||
/** Not locked: do what the way in asked for. */
|
||||
Go,
|
||||
|
||||
/** Locked, and the way in means to speak: stay over the lock screen and listen; what is heard waits for the unlock. */
|
||||
Listen,
|
||||
|
||||
/** Locked, with a question handed over: it is shown and waits for the unlock. */
|
||||
Hold,
|
||||
|
||||
/** Locked, anything else: ask Android to unlock first; the sheet goes if that is turned down. */
|
||||
Unlock,
|
||||
}
|
||||
|
||||
/**
|
||||
* What a sheet opened while the phone is [locked] does. The wake word with the screen off, and a
|
||||
* headset's button, open it listening ([Opening.Listen]) and nobody is there to unlock: asking
|
||||
* Android to unlock first -- and closing when that is cancelled, which is what happens when
|
||||
* nobody answers the lock screen -- showed the sheet for a moment and took it away again. So it
|
||||
* stays and listens, and only *sending* waits for the unlock. Without the microphone's
|
||||
* permission there is nothing to listen with, and its prompt needs the phone unlocked anyway.
|
||||
*/
|
||||
fun lockedStart(locked: Boolean, opening: Opening, question: Boolean, micAllowed: Boolean): LockedStart = when {
|
||||
!locked -> LockedStart.Go
|
||||
question -> LockedStart.Hold
|
||||
opening == Opening.Listen && micAllowed -> LockedStart.Listen
|
||||
else -> LockedStart.Unlock
|
||||
}
|
||||
|
||||
/**
|
||||
* The assistant as an activity: what the Quick Settings tile, the "Ask" shortcut and a plain
|
||||
@@ -23,10 +96,18 @@ import eu.llembas.android.ui.theme.LembasTheme
|
||||
* activity -- a question asked over the lock screen, or the microphone's permission prompt
|
||||
* ([EXTRA_LISTEN]). The same sheet as the session's, in a see-through window over the app
|
||||
* underneath. Shown over the lock screen, but it asks Android to unlock before it sends
|
||||
* anything -- and shows nothing from the account until then.
|
||||
* anything -- and shows nothing from the account until then. Opened there to listen (the wake
|
||||
* word, a headset's button) it stays up and listens; the question it heard is shown and waits
|
||||
* for the unlock ([lockedStart]).
|
||||
*/
|
||||
class AssistActivity : ComponentActivity() {
|
||||
private lateinit var controller: AssistController
|
||||
private lateinit var keyguard: KeyguardManager
|
||||
private var started = false
|
||||
private var byWake = false
|
||||
|
||||
/** The screen went off since the sheet was last seen: on the way back, the lock is looked at again. */
|
||||
private var wentOff = false
|
||||
|
||||
/** Whether the phone is locked: the sheet shows nothing from the account until it is not. */
|
||||
private val locked = mutableStateOf(false)
|
||||
@@ -34,6 +115,29 @@ class AssistActivity : ComponentActivity() {
|
||||
if (granted) controller.listen()
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone was unlocked by the person themselves (a fingerprint while the sheet is up): the
|
||||
* question that waited is sent. And the screen went off: the microphone and the voice stop
|
||||
* at once, whatever the lock says yet, and nothing of the conversation is left in the
|
||||
* picture the phone keeps of the sheet; a sheet that was over the lock screen goes, so that
|
||||
* it is not what the phone shows when it is next picked up.
|
||||
*/
|
||||
private val screen = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
Intent.ACTION_USER_PRESENT -> unlockedNow()
|
||||
|
||||
Intent.ACTION_SCREEN_OFF -> {
|
||||
val overLock = locked.value
|
||||
wentOff = true
|
||||
if (keyguard.isKeyguardLocked) controller.lockedNow() else controller.screenOff()
|
||||
locked.value = true
|
||||
if (overLock) finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
@@ -41,30 +145,40 @@ class AssistActivity : ComponentActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
setShowWhenLocked(true)
|
||||
controller = AssistController(this, lifecycleScope)
|
||||
val keyguard = getSystemService(KeyguardManager::class.java)
|
||||
keyguard = getSystemService(KeyguardManager::class.java)
|
||||
locked.value = keyguard.isKeyguardLocked
|
||||
val waiting = intent.getStringExtra(EXTRA_QUESTION).orEmpty()
|
||||
val wantsMic = intent.getBooleanExtra(EXTRA_LISTEN, false)
|
||||
if (keyguard.isKeyguardLocked) {
|
||||
keyguard.requestDismissKeyguard(
|
||||
this,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() {
|
||||
locked.value = false
|
||||
if (waiting.isNotBlank()) controller.ask(waiting) else controller.opened(locked = false)
|
||||
}
|
||||
|
||||
override fun onDismissCancelled() = finish()
|
||||
|
||||
override fun onDismissError() = finish()
|
||||
},
|
||||
)
|
||||
} else if (waiting.isNotBlank()) {
|
||||
controller.ask(waiting)
|
||||
} else if (wantsMic && !controller.micAllowed()) {
|
||||
mic.launch(Manifest.permission.RECORD_AUDIO)
|
||||
ContextCompat.registerReceiver(
|
||||
this,
|
||||
screen,
|
||||
IntentFilter().apply {
|
||||
addAction(Intent.ACTION_USER_PRESENT)
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
},
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
// A question waits for the unlock: Android is asked for it at once (a face or a
|
||||
// fingerprint is then enough), and the sheet stays if nobody answers.
|
||||
lifecycleScope.launch {
|
||||
controller.state.map { it.held }.distinctUntilChanged().collect { held ->
|
||||
if (held && locked.value) askToUnlock()
|
||||
}
|
||||
}
|
||||
// The lock screen turns the display off after a few seconds: not in the middle of a
|
||||
// question, and not in the middle of an answer read aloud (the screen going off stops it).
|
||||
lifecycleScope.launch {
|
||||
controller.state.map { it.listening || it.busy || it.speaking }.distinctUntilChanged().collect { on ->
|
||||
if (on) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) else window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
}
|
||||
}
|
||||
// Opened by the wake word: the screen comes on with it (a spoken phrase is not a touch,
|
||||
// so nothing else has woken the phone).
|
||||
woken(intent)
|
||||
// Once: made again by Android (after the app was put away and brought back), the sheet
|
||||
// must not ask the same question a second time. What waited for the unlock is kept.
|
||||
if (savedInstanceState == null) {
|
||||
take(intent)
|
||||
} else {
|
||||
controller.opened(locked = false)
|
||||
savedInstanceState.getString(STATE_WAITING)?.let { controller.hold(Held(it, null, savedInstanceState.getBoolean(STATE_SPOKEN))) }
|
||||
}
|
||||
setContent {
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
@@ -73,15 +187,13 @@ class AssistActivity : ComponentActivity() {
|
||||
controller = controller,
|
||||
locked = locked.value,
|
||||
onUnlockAndAsk = { text ->
|
||||
keyguard.requestDismissKeyguard(
|
||||
this@AssistActivity,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() {
|
||||
locked.value = false
|
||||
if (text.isBlank()) controller.opened(locked = false) else controller.ask(text)
|
||||
}
|
||||
},
|
||||
)
|
||||
// Typed over the lock screen: held (in the place of a question that
|
||||
// waited already), so that whichever way the unlock is heard of first,
|
||||
// one question is asked, once.
|
||||
val waited = controller.state.value.held
|
||||
if (text.isNotBlank()) controller.ask(text)
|
||||
// A first held question asks Android to unlock by itself (onCreate).
|
||||
if (waited || text.isBlank()) askToUnlock { if (text.isBlank()) controller.opened() }
|
||||
},
|
||||
onOpenApp = {
|
||||
startActivity(controller.appIntent())
|
||||
@@ -89,20 +201,195 @@ class AssistActivity : ComponentActivity() {
|
||||
},
|
||||
onNeedMic = { mic.launch(Manifest.permission.RECORD_AUDIO) },
|
||||
onDismiss = { finish() },
|
||||
onUnlock = { askToUnlock() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Opened again while it is up -- the headset's button pressed twice, the tile again, the wake word. */
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
woken(intent)
|
||||
// The same sheet answers again: it is up, and whoever asked for it is told so.
|
||||
if (started) AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
take(intent)
|
||||
}
|
||||
|
||||
/**
|
||||
* Opened by the wake word: the screen comes on with it (a spoken phrase is not a touch, so
|
||||
* nothing else has woken the phone), and the sheet is remembered as the wake word's, so that
|
||||
* the assistant's own sheet can take its place if that one comes after all.
|
||||
*/
|
||||
private fun woken(intent: Intent?) {
|
||||
byWake = OwnIntents.isOwn(this, intent) && intent?.getBooleanExtra(EXTRA_WAKE, false) == true
|
||||
if (byWake) setTurnScreenOn(true)
|
||||
}
|
||||
|
||||
/**
|
||||
* On screen: only now is the sheet "up" -- for the wake word's pause (which must end when the
|
||||
* sheet is left with Home, not only when it is destroyed) and for whoever waits to hear that
|
||||
* it opened.
|
||||
*/
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
started = true
|
||||
// The phone may have locked, or been unlocked, while the sheet was out of sight.
|
||||
if (keyguard.isKeyguardLocked) {
|
||||
// Found locked: the controller is told, unless the sheet was opened over the lock
|
||||
// screen in the first place (and is listening there).
|
||||
if (!locked.value || wentOff) controller.lockedNow()
|
||||
locked.value = true
|
||||
} else {
|
||||
unlockedNow()
|
||||
}
|
||||
wentOff = false
|
||||
open = WeakReference(this)
|
||||
AssistPresence.shown()
|
||||
AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
// "Heard you. Tap to ask." has been answered, however the sheet was opened.
|
||||
getSystemService(NotificationManager::class.java).cancel(WakeWordService.HEARD_ID)
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
started = false
|
||||
if (open?.get() === this) open = null
|
||||
AssistPresence.hidden()
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
/**
|
||||
* What the way in asked for: a question handed over by the session ([AssistHandOff]),
|
||||
* listening (the headset's voice button, the widget's microphone, the Speak shortcut, the
|
||||
* wake word), the last assistant chat (the widget, the shortcut), or just the sheet. Over
|
||||
* the lock screen: [lockedStart]. Only an intent the app made itself ([OwnIntents]) can
|
||||
* hand over a question or ask for more than Android's own actions do.
|
||||
*/
|
||||
private fun take(intent: Intent) {
|
||||
val own = OwnIntents.isOwn(this, intent)
|
||||
val opening = Opening.of(intent, own)
|
||||
val handed = if (own) AssistHandOff.take(intent.getStringExtra(EXTRA_HANDOFF)) else null
|
||||
val go = {
|
||||
when {
|
||||
handed != null -> controller.hold(handed)
|
||||
opening == Opening.Continue -> controller.continueWhenReady()
|
||||
opening == Opening.Listen && !controller.micAllowed() -> mic.launch(Manifest.permission.RECORD_AUDIO)
|
||||
opening == Opening.Listen -> controller.opened(listen = true)
|
||||
else -> controller.opened()
|
||||
}
|
||||
}
|
||||
val isLocked = keyguard.isKeyguardLocked
|
||||
if (isLocked) locked.value = true
|
||||
when (lockedStart(isLocked, opening, handed != null, controller.micAllowed())) {
|
||||
// Not locked, a handed-over question is asked at once ([AssistController.hold]).
|
||||
LockedStart.Go -> go()
|
||||
|
||||
LockedStart.Listen -> controller.opened(listen = true)
|
||||
|
||||
// Shown, and Android asked to unlock (the collector in onCreate): it stays if nobody does.
|
||||
LockedStart.Hold -> handed?.let { controller.hold(it) }
|
||||
|
||||
LockedStart.Unlock -> keyguard.requestDismissKeyguard(
|
||||
this,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() {
|
||||
unlockedNow()
|
||||
go()
|
||||
}
|
||||
|
||||
override fun onDismissCancelled() = finish()
|
||||
|
||||
override fun onDismissError() = finish()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask Android to unlock. When it does, the question that waited is sent and [then] runs.
|
||||
* When it does not -- nobody there, or Back on the lock screen -- nothing happens: the sheet
|
||||
* stays as it is, with the way to try again.
|
||||
*/
|
||||
private fun askToUnlock(then: () -> Unit = {}) {
|
||||
keyguard.requestDismissKeyguard(
|
||||
this,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() {
|
||||
unlockedNow()
|
||||
then()
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone is unlocked now, however that was heard of -- Android's answer to the asking,
|
||||
* the person's own unlock, the sheet coming back: once, and only if the lock itself says so.
|
||||
*/
|
||||
private fun unlockedNow() {
|
||||
if (!locked.value || keyguard.isKeyguardLocked) return
|
||||
locked.value = false
|
||||
controller.unlocked()
|
||||
}
|
||||
|
||||
/** A question that waits for the unlock outlives the sheet being made again; a recording does not. */
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
val waiting = controller.state.value.waiting
|
||||
if (waiting.isNotBlank()) {
|
||||
outState.putString(STATE_WAITING, waiting)
|
||||
outState.putBoolean(STATE_SPOKEN, controller.heldSpoken)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
runCatching { unregisterReceiver(screen) }
|
||||
controller.close()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_QUESTION = "eu.llembas.android.QUESTION"
|
||||
/** The ticket of a question handed over by the session ([AssistHandOff]); never the question. */
|
||||
const val EXTRA_HANDOFF = "eu.llembas.android.HANDOFF"
|
||||
|
||||
private const val STATE_WAITING = "waiting"
|
||||
private const val STATE_SPOKEN = "spoken"
|
||||
|
||||
/** Handed over by the session: ask for the microphone, then listen. */
|
||||
const val EXTRA_LISTEN = "eu.llembas.android.LISTEN"
|
||||
|
||||
/** Open listening: the widget's microphone and the Speak shortcut. */
|
||||
const val ACTION_LISTEN = "eu.llembas.android.action.LISTEN"
|
||||
|
||||
/** Open at the last chat the assistant made: the widget and the shortcut. */
|
||||
const val ACTION_CONTINUE = "eu.llembas.android.action.CONTINUE"
|
||||
|
||||
/** The sheet, listening. */
|
||||
fun listening(context: Context): Intent = OwnIntents.own(context, Intent(context, AssistActivity::class.java).setAction(ACTION_LISTEN))
|
||||
|
||||
/** The sheet that is on screen now, if this activity is it. */
|
||||
@Volatile
|
||||
private var open: WeakReference<AssistActivity>? = null
|
||||
|
||||
/** The assistant's own sheet came up: a sheet the wake word had opened in its place goes. */
|
||||
fun closeWoken() {
|
||||
open?.get()?.takeIf { it.byWake }?.finish()
|
||||
}
|
||||
|
||||
/** On the intent the wake word opens the sheet with: turn the screen on. */
|
||||
const val EXTRA_WAKE = "eu.llembas.android.WAKE"
|
||||
|
||||
/** The sheet, listening, as the wake word opens it. */
|
||||
fun woken(context: Context): Intent = listening(context).putExtra(EXTRA_WAKE, true).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
|
||||
/** The sheet, at the last assistant chat. */
|
||||
fun continuing(context: Context): Intent = OwnIntents.own(context, Intent(context, AssistActivity::class.java).setAction(ACTION_CONTINUE))
|
||||
|
||||
/** The sheet, taking the question left under [ticket] -- or asking for the microphone and listening. */
|
||||
fun handedOver(context: Context, ticket: String?, listen: Boolean): Intent = OwnIntents.own(
|
||||
context,
|
||||
Intent(context, AssistActivity::class.java).putExtra(EXTRA_HANDOFF, ticket).putExtra(EXTRA_LISTEN, listen).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,48 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.Bitmap
|
||||
import android.os.SystemClock
|
||||
import android.speech.SpeechRecognizer
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.MediaFor
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.notify.NotificationAccess
|
||||
import eu.llembas.android.notify.NotificationReader
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.ui.explain
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.transformWhile
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import java.io.ByteArrayOutputStream
|
||||
@@ -38,6 +53,12 @@ data class AssistTurn(val question: String, val reply: LiveReply? = null, val ea
|
||||
val writing: Boolean get() = reply != null && reply.finished == null && !reply.closed
|
||||
}
|
||||
|
||||
/**
|
||||
* A question that waits for the phone to be unlocked: its [text], or -- heard where the instance
|
||||
* writes speech down -- its recording ([wav]), which stays on the phone until then.
|
||||
*/
|
||||
class Held(val text: String, val wav: ByteArray?, val spoken: Boolean)
|
||||
|
||||
/** Whether the instance answers: being asked, yes, or no (and why). */
|
||||
enum class Connection { Checking, Online, Offline }
|
||||
|
||||
@@ -50,6 +71,8 @@ data class AssistUiState(
|
||||
val connection: Connection = Connection.Checking,
|
||||
val models: List<ModelInfo> = emptyList(),
|
||||
val modelId: String? = null,
|
||||
/** [modelId] is a continued chat's own `model_ref`: looked up as a ref alone, never as an id. */
|
||||
val modelIsRef: Boolean = false,
|
||||
val listening: Boolean = false,
|
||||
/** The words heard so far, while listening and while the last of them is written down. */
|
||||
val heard: String = "",
|
||||
@@ -71,9 +94,30 @@ data class AssistUiState(
|
||||
val speaking: Boolean = false,
|
||||
/** Whether anything can turn speech into words: the instance's speech-to-text, or the phone's. */
|
||||
val canListen: Boolean = true,
|
||||
/**
|
||||
* A spoken conversation: after each spoken answer is read aloud, the sheet listens again --
|
||||
* until the person says stop, taps End, types, or says nothing.
|
||||
*/
|
||||
val conversation: Boolean = false,
|
||||
/** Whether the person let the assistant read the notifications when asked (Settings and Android both). */
|
||||
val canReadNotifications: Boolean = false,
|
||||
/**
|
||||
* A question that waits for the phone to be unlocked: typed over the lock screen, or heard
|
||||
* there by the phone's own recogniser -- the person's own words and nothing from the
|
||||
* account. Asked once the phone is unlocked.
|
||||
*/
|
||||
val waiting: String = "",
|
||||
/**
|
||||
* A question heard over the lock screen that waits as a recording, on the phone: the
|
||||
* instance writes speech down, and nothing goes to the instance while the phone is locked.
|
||||
*/
|
||||
val waitingRecording: Boolean = false,
|
||||
) {
|
||||
/** Whether a question waits for the unlock, as words or as a recording. */
|
||||
val held: Boolean get() = waiting.isNotBlank() || waitingRecording
|
||||
|
||||
val screenAvailable: Boolean get() = screenText || screenshot != null
|
||||
val modelInfo: ModelInfo? get() = models.firstOrNull { it.id == modelId }
|
||||
val modelInfo: ModelInfo? get() = models.named(modelId, modelIsRef)
|
||||
val empty: Boolean get() = turns.isEmpty()
|
||||
}
|
||||
|
||||
@@ -94,6 +138,9 @@ interface AssistActions {
|
||||
fun voiceReply(on: Boolean) {}
|
||||
fun readAloud() {}
|
||||
fun stopReading() {}
|
||||
fun endConversation() {}
|
||||
fun summariseNotifications() {}
|
||||
fun answerCard(card: Card, answer: CardAnswer) {}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -110,26 +157,82 @@ interface AssistActions {
|
||||
* a moment behind, from the recording so far, and a pause in speech sends it), or the phone's
|
||||
* own recogniser (the words as they are said). Speech out is the instance's text-to-speech.
|
||||
*/
|
||||
class AssistController(private val context: Context, private val scope: CoroutineScope) : AssistActions {
|
||||
class AssistController(
|
||||
private val context: Context,
|
||||
private val scope: CoroutineScope,
|
||||
/**
|
||||
* Whether the phone is locked, asked each time it matters. While it is, nothing goes to the
|
||||
* instance from here: no question, no recording to write down, not even "which models".
|
||||
*/
|
||||
private val locked: () -> Boolean = { context.getSystemService(KeyguardManager::class.java)?.isKeyguardLocked == true },
|
||||
) : AssistActions {
|
||||
private val _state = MutableStateFlow(AssistUiState())
|
||||
val state = _state.asStateFlow()
|
||||
private val recorder = Recorder(scope)
|
||||
private val phone = PhoneRecognizer(context)
|
||||
private val speaker = Speaker(context)
|
||||
private val route = HeadsetRoute(context)
|
||||
private var following: Job? = null
|
||||
private var hearing: Job? = null
|
||||
|
||||
/** The ear for the end of speech, while the instance's speech-to-text listens. */
|
||||
private var ear: EndOfSpeech? = null
|
||||
private var usingPhone = false
|
||||
private var screenText: String? = null
|
||||
private var stt: Boolean? = null
|
||||
private val ready: Job
|
||||
|
||||
/** The account's own default model, as the instance said it: what "Instance default" means. */
|
||||
private var accountDefault: String? = null
|
||||
|
||||
/**
|
||||
* The model a new chat starts on (Settings › Assistant › Assistant model). The sheet's
|
||||
* [AssistUiState.modelId] is the model of the chat it is in, which for a continued chat is
|
||||
* that chat's own; a new chat goes back to this one.
|
||||
*/
|
||||
private var newChatModel: String? = null
|
||||
|
||||
/** The question that waits for the unlock ([hold]). */
|
||||
private var held: Held? = null
|
||||
|
||||
/** Whether the question that waits was spoken. */
|
||||
val heldSpoken: Boolean get() = held?.spoken == true
|
||||
|
||||
/** When the phone's recogniser last gave a sign of somebody speaking (elapsed ms). */
|
||||
private var phoneActiveAt = 0L
|
||||
|
||||
/** What the phone itself knows: Settings, the instance's name. */
|
||||
private val local: Job
|
||||
|
||||
/** What the instance says -- its models, what it offers: asked only once the phone is unlocked. */
|
||||
private var remote: Job? = null
|
||||
|
||||
init {
|
||||
ready = scope.launch { load() }
|
||||
local = scope.launch {
|
||||
loadLocal()
|
||||
if (!locked()) askInstance()
|
||||
}
|
||||
scope.launch { speaker.playing.collect { on -> _state.update { it.copy(speaking = on) } } }
|
||||
// Settings changed the assistant's model while this sheet lives: the next new chat has it.
|
||||
scope.launch {
|
||||
context.lembas.instances.prefs.map { it.assistantModel }.distinctUntilChanged().drop(1).collect { chosen ->
|
||||
ready()
|
||||
newChatModel = assistantModelFor(chosen, accountDefault, _state.value.models) ?: chosen.ifBlank { null }
|
||||
_state.update { if (it.chatId == null) it.copy(modelId = newChatModel, modelIsRef = false) else it }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The instance, its models and what it offers this account; the choices kept in Settings. */
|
||||
private suspend fun load() {
|
||||
/** Everything known: Settings, and -- unless the phone is locked -- what the instance says. */
|
||||
private suspend fun ready() {
|
||||
local.join()
|
||||
if (!locked()) askInstance().join()
|
||||
}
|
||||
|
||||
/** Ask the instance what it has, once. */
|
||||
private fun askInstance(): Job = remote ?: scope.launch { loadRemote() }.also { remote = it }
|
||||
|
||||
/** The choices kept in Settings, and which instance: nothing here leaves the phone. */
|
||||
private suspend fun loadLocal() {
|
||||
val store = context.lembas.instances
|
||||
val instance = store.current()
|
||||
val prefs = store.prefs.first()
|
||||
@@ -138,19 +241,28 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
signedIn = instance != null,
|
||||
instanceName = instance?.name?.ifBlank { instance.base }.orEmpty(),
|
||||
voiceReply = prefs.readAloudSpoken,
|
||||
canReadNotifications = prefs.notificationSummaries && NotificationAccess.granted(context),
|
||||
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
|
||||
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
|
||||
)
|
||||
}
|
||||
val api = instance?.let { store.clientFor(it) } ?: return
|
||||
// Until the instance has said what it has, the choice in Settings stands as it is: a
|
||||
// question asked while the list could not be read still goes to the chosen model.
|
||||
newChatModel = prefs.assistantModel.ifBlank { null }
|
||||
}
|
||||
|
||||
/** The instance's models and what it offers this account. */
|
||||
private suspend fun loadRemote() {
|
||||
val store = context.lembas.instances
|
||||
val prefs = store.prefs.first()
|
||||
val api = store.current()?.let { store.clientFor(it) } ?: return
|
||||
try {
|
||||
val me = api.me()
|
||||
val models = api.models()
|
||||
stt = me.speechToText
|
||||
val chosen = prefs.assistantModel.takeIf { id -> models.any { it.id == id } }
|
||||
?: me.defaultModel?.takeIf { id -> models.any { it.id == id } }
|
||||
?: models.firstOrNull { it.default }?.id
|
||||
?: models.firstOrNull()?.id
|
||||
accountDefault = me.defaultModel
|
||||
val chosen = assistantModelFor(prefs.assistantModel, me.defaultModel, models)
|
||||
newChatModel = chosen
|
||||
_state.update {
|
||||
it.copy(
|
||||
connection = Connection.Online,
|
||||
@@ -167,15 +279,101 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
|
||||
/**
|
||||
* The sheet came up. It starts listening at once -- the microphone first, as an assistant
|
||||
* opens -- unless Settings says not to, the phone is locked (nothing is sent from the lock
|
||||
* screen), or the microphone is not allowed yet (that needs an activity to ask).
|
||||
* opens -- unless Settings says not to or the microphone is not allowed yet (that needs an
|
||||
* activity to ask). [listen] is a way in that means to speak -- the wake word, a headset's
|
||||
* voice button -- and listens regardless.
|
||||
*
|
||||
* Over the lock screen only such a way in listens, and what it hears is held for the unlock
|
||||
* ([hold]), never asked from there; the microphone opens without waiting for the instance.
|
||||
*/
|
||||
fun opened(locked: Boolean) {
|
||||
fun opened(listen: Boolean = false) {
|
||||
scope.launch {
|
||||
ready.join()
|
||||
if (locked()) {
|
||||
local.join()
|
||||
val s = _state.value
|
||||
if (listen && s.signedIn && !s.listening && !s.held && micAllowed()) listen()
|
||||
return@launch
|
||||
}
|
||||
ready()
|
||||
val prefs = context.lembas.instances.prefs.first()
|
||||
val s = _state.value
|
||||
if (s.signedIn && !locked && prefs.assistantListens && s.canListen && s.empty && !s.listening && micAllowed()) listen()
|
||||
if (s.signedIn && (listen || prefs.assistantListens) && s.canListen && !s.listening && micAllowed()) {
|
||||
if (listen || s.empty) listen()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep [question] until the phone is unlocked ([unlocked]); it takes the place of one that
|
||||
* waited already. With the phone not locked there is nothing to wait for.
|
||||
*/
|
||||
fun hold(question: Held) {
|
||||
if (question.text.isBlank() && question.wav == null) return
|
||||
held = question
|
||||
_state.update { it.copy(waiting = question.text, waitingRecording = question.wav != null, conversation = false) }
|
||||
if (!locked()) unlocked()
|
||||
}
|
||||
|
||||
/** The question that waits, taken away from here: to be handed to another sheet. */
|
||||
fun takeHeld(): Held? {
|
||||
val waited = held
|
||||
held = null
|
||||
_state.update { it.copy(waiting = "", waitingRecording = false) }
|
||||
return waited
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone is unlocked: the instance is asked what it has, and the question that waited is
|
||||
* asked now -- a recording is written down first. Does nothing while the phone is still locked.
|
||||
*/
|
||||
fun unlocked() {
|
||||
if (locked()) return
|
||||
askInstance()
|
||||
val waited = takeHeld() ?: return
|
||||
val wav = waited.wav
|
||||
if (wav == null) {
|
||||
ask(waited.text, spoken = waited.spoken)
|
||||
return
|
||||
}
|
||||
scope.launch {
|
||||
try {
|
||||
_state.update { it.copy(busy = true, error = null) }
|
||||
val text = context.lembas.instances.client()?.transcribe(wav, media = mediaFor())?.text.orEmpty()
|
||||
_state.update { it.copy(busy = false) }
|
||||
if (text.isNotBlank()) ask(text, spoken = true)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(busy = false, error = context.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The screen went off: the microphone and the voice stop, whatever the lock says -- nobody
|
||||
* is looking, and a phone that is about to lock must not go on listening or talking.
|
||||
*/
|
||||
fun screenOff() {
|
||||
speaker.stop()
|
||||
if (_state.value.listening) type()
|
||||
_state.update { it.copy(conversation = false) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone locked while the sheet was up: as [screenOff], and the answer being written is
|
||||
* no longer followed. Whatever is asked from now on waits for the unlock ([ask]).
|
||||
*/
|
||||
fun lockedNow() {
|
||||
screenOff()
|
||||
following?.cancel()
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
|
||||
/** Open at the last assistant chat, once it is known which that is. */
|
||||
fun continueWhenReady() {
|
||||
scope.launch {
|
||||
ready()
|
||||
if (_state.value.last != null) continueLast() else opened()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,13 +402,19 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
_state.update { it.copy(listening = true, heard = "", level = 0f, error = null) }
|
||||
hearing = scope.launch {
|
||||
usingPhone = phoneEngine()
|
||||
// A headset's microphone when one is there: the conversation can go on in the ear.
|
||||
val headset = route.microphone()
|
||||
if (usingPhone) {
|
||||
phone.start(
|
||||
onPartial = { words -> _state.update { it.copy(heard = words) } },
|
||||
onPartial = { words ->
|
||||
phoneActiveAt = SystemClock.elapsedRealtime()
|
||||
_state.update { it.copy(heard = words) }
|
||||
},
|
||||
onActive = { phoneActiveAt = SystemClock.elapsedRealtime() },
|
||||
onLevel = { l -> _state.update { it.copy(level = l) } },
|
||||
onResult = { words ->
|
||||
_state.update { it.copy(listening = false, level = 0f, heard = "") }
|
||||
if (words.isNotBlank()) ask(words, spoken = true)
|
||||
if (words.isNotBlank()) askOrStop(words) else endConversation()
|
||||
},
|
||||
onFail = { code ->
|
||||
val quiet = code == SpeechRecognizer.ERROR_NO_MATCH || code == SpeechRecognizer.ERROR_SPEECH_TIMEOUT
|
||||
@@ -218,12 +422,16 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
it.copy(
|
||||
listening = false,
|
||||
level = 0f,
|
||||
conversation = false,
|
||||
error = if (quiet) null else context.getString(R.string.assist_recogniser_failed),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
watchPhone()
|
||||
} else {
|
||||
recorder.preferred = headset
|
||||
ear = EndOfSpeech(TICK_MS)
|
||||
recorder.start()
|
||||
launch { recorder.level.collect { l -> _state.update { it.copy(level = l) } } }
|
||||
launch { writeDownAsSaid() }
|
||||
@@ -237,7 +445,9 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
/**
|
||||
* The instance's speech-to-text takes a whole recording, so words "as they are said" are the
|
||||
* recording so far, written down again every moment -- one request at a time, only when half
|
||||
* a second more has been said, and not past the first minute.
|
||||
* a second more has been said, not past the first minute -- and not before the microphone
|
||||
* has heard anything above the room: silence written down is an invented sentence. Never
|
||||
* while the phone is locked: the recording stays on the phone until it is unlocked.
|
||||
*/
|
||||
private suspend fun writeDownAsSaid() {
|
||||
val api = context.lembas.instances.client() ?: return
|
||||
@@ -245,44 +455,75 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
while (scope.isActive) {
|
||||
delay(PARTIAL_EVERY_MS)
|
||||
val seconds = recorder.seconds
|
||||
if (seconds - sent < 0.5f || seconds > 60f) continue
|
||||
if (seconds - sent < 0.5f || seconds > 60f || ear?.heardSomething != true || locked()) continue
|
||||
sent = seconds
|
||||
val words = runCatching { api.transcribe(recorder.snapshot()) }.getOrNull()
|
||||
val words = runCatching { api.transcribe(recorder.snapshot(), media = mediaFor()).text }.getOrNull()
|
||||
if (!words.isNullOrBlank() && _state.value.listening) _state.update { it.copy(heard = words) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Wait for a pause after speech (true) -- or for nothing said at all, which gives up (false). */
|
||||
/**
|
||||
* Wait for a pause after speech (true) -- or for nothing said at all, which gives up (false).
|
||||
* [EndOfSpeech] decides, from the microphone's level against the room's own and the words
|
||||
* written down so far.
|
||||
*/
|
||||
private suspend fun untilQuiet(): Boolean {
|
||||
var spoke = false
|
||||
var quietFor = 0L
|
||||
var waited = 0L
|
||||
// The words written down so far are the second ear, for a quiet microphone: words the
|
||||
// instance heard mean speech, and the same words for a while mean it ended.
|
||||
var words = ""
|
||||
var sameWordsFor = 0L
|
||||
val ear = ear ?: return false
|
||||
while (true) {
|
||||
delay(TICK_MS)
|
||||
waited += TICK_MS
|
||||
val level = recorder.level.value
|
||||
if (level >= SPEAKING) {
|
||||
spoke = true
|
||||
quietFor = 0
|
||||
} else if (level < QUIET) {
|
||||
quietFor += TICK_MS
|
||||
// Over the lock screen no words are written down: the level alone decides.
|
||||
when (ear.tick(recorder.level.value, _state.value.heard)) {
|
||||
EndOfSpeech.Verdict.Said -> return true
|
||||
EndOfSpeech.Verdict.Nothing -> return false
|
||||
EndOfSpeech.Verdict.Listening -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone's recogniser finds the end of speech itself -- and is watched all the same
|
||||
* ([phoneWatch]): one that never calls back would leave the sheet listening for good.
|
||||
*/
|
||||
private suspend fun watchPhone() {
|
||||
var waited = 0L
|
||||
var words = ""
|
||||
var sameFor = 0L
|
||||
var asked = false
|
||||
val began = SystemClock.elapsedRealtime()
|
||||
phoneActiveAt = 0L
|
||||
while (_state.value.listening) {
|
||||
delay(TICK_MS)
|
||||
waited += TICK_MS
|
||||
val heard = _state.value.heard
|
||||
if (heard.isNotBlank()) spoke = true
|
||||
if (heard != words) {
|
||||
words = heard
|
||||
sameWordsFor = 0
|
||||
} else if (heard.isNotBlank()) {
|
||||
sameWordsFor += TICK_MS
|
||||
sameFor = 0
|
||||
} else {
|
||||
sameFor += TICK_MS
|
||||
}
|
||||
// Since it last gave a sign of somebody speaking; never, and it is as long as it has listened.
|
||||
val silentFor = if (phoneActiveAt >= began) SystemClock.elapsedRealtime() - phoneActiveAt else waited
|
||||
when (phoneWatch(waited, heard.isNotBlank(), sameFor, silentFor)) {
|
||||
PhoneWatch.Wait -> Unit
|
||||
|
||||
PhoneWatch.Finish -> if (!asked) {
|
||||
asked = true
|
||||
phone.finish()
|
||||
}
|
||||
|
||||
PhoneWatch.Take -> {
|
||||
phone.stop()
|
||||
_state.update { it.copy(listening = false, level = 0f, heard = "") }
|
||||
askOrStop(heard)
|
||||
return
|
||||
}
|
||||
|
||||
PhoneWatch.GiveUp -> {
|
||||
phone.stop()
|
||||
_state.update { it.copy(listening = false, level = 0f, heard = "", conversation = false) }
|
||||
return
|
||||
}
|
||||
}
|
||||
if (spoke && quietFor >= PAUSE_MS) return true
|
||||
if (sameWordsFor >= SAME_WORDS_MS) return true
|
||||
if (!spoke && waited >= NOTHING_SAID_MS) return false
|
||||
if (waited >= LONGEST_MS) return spoke
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,24 +543,45 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
_state.update { it.copy(heard = "") }
|
||||
return@launch
|
||||
}
|
||||
// Over the lock screen nothing goes to the instance, a recording to write down
|
||||
// included: it waits on the phone, and is written down and asked on the unlock.
|
||||
if (locked()) {
|
||||
_state.update { it.copy(heard = "") }
|
||||
hold(Held("", wav, spoken = true))
|
||||
return@launch
|
||||
}
|
||||
try {
|
||||
_state.update { it.copy(busy = true) }
|
||||
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
val text = context.lembas.instances.client()?.transcribe(wav, media = mediaFor())?.text.orEmpty()
|
||||
_state.update { it.copy(busy = false, heard = "") }
|
||||
if (text.isNotBlank()) ask(text, spoken = true)
|
||||
if (text.isNotBlank()) askOrStop(text) else endConversation()
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(busy = false, heard = "", error = context.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop listening and keep nothing: the person would rather type. */
|
||||
/**
|
||||
* Stop listening and keep nothing: the person would rather type -- or said nothing at all.
|
||||
* Either ends a spoken conversation.
|
||||
*/
|
||||
override fun type() {
|
||||
hearing?.cancel()
|
||||
hearing = null
|
||||
phone.stop()
|
||||
scope.launch { recorder.stop() }
|
||||
_state.update { it.copy(listening = false, heard = "", level = 0f) }
|
||||
_state.update { it.copy(listening = false, heard = "", level = 0f, conversation = false) }
|
||||
}
|
||||
|
||||
/** What was said: in a conversation, "stop" (or the like) ends it; anything else is asked. */
|
||||
private fun askOrStop(words: String) {
|
||||
if (locked()) return hold(Held(words, null, spoken = true))
|
||||
val phrases = context.getString(R.string.assist_stop_words).split("|")
|
||||
if (_state.value.conversation && isStopPhrase(words, phrases)) endConversation() else ask(words, spoken = true)
|
||||
}
|
||||
|
||||
override fun endConversation() {
|
||||
_state.update { it.copy(conversation = false) }
|
||||
}
|
||||
|
||||
// --- Asking ------------------------------------------------------------------------------
|
||||
@@ -331,23 +593,49 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
ask(prompt, spoken = false)
|
||||
}
|
||||
|
||||
fun ask(question: String, spoken: Boolean) {
|
||||
/** The sheet's "Summarise my notifications": the notifications up now go with the question. */
|
||||
override fun summariseNotifications() = ask(context.getString(R.string.assist_notifications_prompt), spoken = false, notifications = true)
|
||||
|
||||
/**
|
||||
* Ask [question]. With the phone locked it is not asked but held for the unlock, whoever
|
||||
* called: this is the one door to the instance, and it is shut while the phone is locked.
|
||||
*/
|
||||
fun ask(question: String, spoken: Boolean, notifications: Boolean = false) {
|
||||
if (question.isBlank()) return
|
||||
if (locked()) return hold(Held(question, null, spoken))
|
||||
if (_state.value.listening) type()
|
||||
following?.cancel()
|
||||
following = scope.launch {
|
||||
val turn = AssistTurn(question)
|
||||
_state.update { it.copy(busy = true, turns = it.turns + turn, error = null) }
|
||||
// A spoken question, answered aloud, opens a conversation (Settings › Assistant).
|
||||
val talking = spoken && context.lembas.instances.prefs.first().assistantConversation &&
|
||||
_state.value.voiceReply && _state.value.canSpeak
|
||||
_state.update { it.copy(conversation = talking) }
|
||||
try {
|
||||
val store = context.lembas.instances
|
||||
val api = store.client() ?: throw ApiException(401, "Not signed in.")
|
||||
val prefs = store.prefs.first()
|
||||
// A question typed the moment the sheet opened: the model is known first.
|
||||
ready()
|
||||
val now = _state.value
|
||||
val withScreen = now.includeScreen
|
||||
val attachments = buildList {
|
||||
if (withScreen) now.screenshot?.let { shot -> add(api.upload("screen.png", "image/png", png(shot), now.chatId).id) }
|
||||
}
|
||||
val text = if (withScreen && screenText != null) "$question\n\n---\nOn my screen:\n\n$screenText" else question
|
||||
// The notifications, when asked for by the chip or by name ("my notifications") --
|
||||
// read now, only while unlocked (NotificationAccess.read), and for this question only.
|
||||
val phrases = context.getString(R.string.assist_notifications_phrases).split("|")
|
||||
val notices = if (now.canReadNotifications && (notifications || NotificationReader.asksAbout(question, phrases))) {
|
||||
NotificationReader.asText(NotificationAccess.read(context)).ifBlank { NO_NOTIFICATIONS }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val text = buildString {
|
||||
append(question)
|
||||
if (withScreen && screenText != null) append("\n\n---\nOn my screen:\n\n$screenText")
|
||||
if (notices != null) append("\n\n---\nMy notifications:\n\n$notices")
|
||||
}
|
||||
// The screen goes with one question, not every one after it.
|
||||
_state.update { it.copy(includeScreen = false) }
|
||||
val chatId = now.chatId
|
||||
@@ -358,7 +646,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
inChat = chatId
|
||||
replyId = sent.reply?.id ?: return@launch
|
||||
} else {
|
||||
val made = api.createChat(text, attachments, model = now.modelId, temporary = prefs.assistantTemporary)
|
||||
val made = api.createChat(text, attachments, model = now.modelId ?: newChatModel, temporary = prefs.assistantTemporary)
|
||||
inChat = made.chat.id
|
||||
replyId = made.reply?.id ?: return@launch
|
||||
_state.update { it.copy(chatId = inChat) }
|
||||
@@ -369,19 +657,55 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
}
|
||||
}
|
||||
var live = LiveReply(replyId)
|
||||
StreamClient(api).follow(inChat, replyId).collect { frame ->
|
||||
// To `done`, which is the end of the reply: the stream may stay open after it for
|
||||
// the chat's name, and a spoken answer must not wait for that.
|
||||
StreamClient(api).follow(inChat, replyId).transformWhile { frame ->
|
||||
emit(frame)
|
||||
frame.event != "done"
|
||||
}.collect { frame ->
|
||||
live = live.apply(frame.event, frame.data)
|
||||
_state.update { s -> s.copy(turns = s.turns.dropLast(1) + turn.copy(reply = live), busy = live.finished == null) }
|
||||
}
|
||||
if (spoken && _state.value.voiceReply && _state.value.canSpeak && live.finished != null) speak(spokenWords(live.finished?.steps.orEmpty()))
|
||||
// A new chat is named by a model after `done`. The name the sheet offers the chat
|
||||
// under next time is fetched in the background, for a bounded while -- never by
|
||||
// holding the reply's stream open, and never before the answer is spoken.
|
||||
if (live.titlePending && !prefs.assistantTemporary) nameLater(api, inChat, live.title.orEmpty())
|
||||
val heardAll = if (spoken && _state.value.voiceReply && _state.value.canSpeak && live.finished != null && live.cards.isEmpty()) {
|
||||
speak(spokenWords(live.finished?.steps.orEmpty()))
|
||||
} else {
|
||||
false
|
||||
}
|
||||
// The answer was heard to the end: listen for the next thing said. Stopped, a
|
||||
// card waiting, or nothing to read: the conversation ends there.
|
||||
if (_state.value.conversation && heardAll && micAllowed() && !locked()) listen() else endConversation()
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
_state.update { it.copy(error = context.explain(e), conversation = false) }
|
||||
} finally {
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The chat's name once a model has given it: asked for a few times over [TITLE_WAIT_MS], then
|
||||
* left -- the name made from the prompt stands, and the app's list has the real one anyway.
|
||||
*/
|
||||
private fun nameLater(api: ApiClient, chatId: String, provisional: String) {
|
||||
scope.launch {
|
||||
withTimeoutOrNull(TITLE_WAIT_MS) {
|
||||
while (true) {
|
||||
delay(TITLE_ASK_MS)
|
||||
val title = runCatching { api.chat(chatId).chat.title }.getOrNull().orEmpty()
|
||||
if (title.isNotBlank() && title != provisional) {
|
||||
context.lembas.instances.savePrefs { if (it.lastAssistChat == chatId) it.copy(lastAssistTitle = title.take(120)) else it }
|
||||
_state.update { s -> s.copy(last = s.last?.let { l -> if (l.chatId == chatId) l.copy(title = title.take(120)) else l }) }
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Carry on the last chat the assistant made: its last exchange shown, the next question sent to it. */
|
||||
override fun continueLast() {
|
||||
val last = _state.value.last ?: return
|
||||
@@ -393,7 +717,16 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
val question = detail.messages.lastOrNull { it.isUser }
|
||||
val answer = detail.messages.lastOrNull { !it.isUser }
|
||||
val turns = if (question != null) listOf(AssistTurn(question.text.orEmpty(), earlier = answer?.steps.orEmpty())) else emptyList()
|
||||
_state.update { it.copy(chatId = last.chatId, turns = turns, modelId = detail.chat.model.ifBlank { null } ?: it.modelId, last = null) }
|
||||
val own = detail.chat.modelKey
|
||||
_state.update {
|
||||
it.copy(
|
||||
chatId = last.chatId,
|
||||
turns = turns,
|
||||
modelId = own ?: it.modelId,
|
||||
modelIsRef = if (own != null) !detail.chat.modelRef.isNullOrBlank() else it.modelIsRef,
|
||||
last = null,
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// A chat deleted since is simply not offered again.
|
||||
if (e is ApiException && e.status == 404) {
|
||||
@@ -408,15 +741,43 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
}
|
||||
}
|
||||
|
||||
/** A phone action's card, answered in the sheet: what the phone did (spec 3.6.0). */
|
||||
override fun answerCard(card: Card, answer: CardAnswer) {
|
||||
val chat = _state.value.chatId ?: return
|
||||
scope.launch {
|
||||
try {
|
||||
context.lembas.instances.client()?.answer(chat, card.id, answer)
|
||||
} catch (e: ApiException) {
|
||||
// First answer wins: a 409 is somebody answering elsewhere already.
|
||||
if (e.status != 409) _state.update { it.copy(error = context.explain(e)) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun newChat() {
|
||||
following?.cancel()
|
||||
speaker.stop()
|
||||
_state.update { it.copy(chatId = null, turns = emptyList(), error = null, busy = false) }
|
||||
// And on the assistant's own model again, not the one of the chat that was continued.
|
||||
_state.update {
|
||||
it.copy(
|
||||
chatId = null,
|
||||
turns = emptyList(),
|
||||
error = null,
|
||||
busy = false,
|
||||
conversation = false,
|
||||
modelId = newChatModel ?: it.modelId,
|
||||
modelIsRef =
|
||||
newChatModel == null && it.modelIsRef,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** The model: for the chat this sheet is in, changed at once; for a new one, kept for next time. */
|
||||
override fun pickModel(id: String) {
|
||||
_state.update { it.copy(modelId = id) }
|
||||
newChatModel = id
|
||||
_state.update { it.copy(modelId = id, modelIsRef = false) }
|
||||
scope.launch {
|
||||
context.lembas.instances.savePrefs { it.copy(assistantModel = id) }
|
||||
val chat = _state.value.chatId ?: return@launch
|
||||
@@ -438,15 +799,25 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
scope.launch { speak(spokenWords(steps)) }
|
||||
}
|
||||
|
||||
/** Stop the voice -- and, in a conversation, the listening that would follow it. */
|
||||
override fun stopReading() = speaker.stop()
|
||||
|
||||
private suspend fun speak(words: String) {
|
||||
if (words.isBlank()) return
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: return
|
||||
speaker.play(api.speech(words))
|
||||
/**
|
||||
* Which chat the sheet's speech is for: the chat it is in, else the model its next chat
|
||||
* starts on. That a fallback answered is not said here: the sheet may be over the lock.
|
||||
*/
|
||||
private fun mediaFor(): MediaFor = _state.value.let { MediaFor.of(it.chatId, it.modelId ?: newChatModel) }
|
||||
|
||||
/** Read [words] aloud; true when they were heard to the end. */
|
||||
private suspend fun speak(words: String): Boolean {
|
||||
// Never aloud over the lock screen: an answer is the account's.
|
||||
if (words.isBlank() || locked()) return false
|
||||
return try {
|
||||
val api = context.lembas.instances.client() ?: return false
|
||||
speaker.playToEnd(api.speech(words, mediaFor()).audio)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -461,7 +832,10 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
hearing?.cancel()
|
||||
speaker.stop()
|
||||
phone.stop()
|
||||
scope.launch { recorder.stop() }
|
||||
route.release()
|
||||
// Not in a coroutine: the scope may be cancelled already, and the microphone must be let go.
|
||||
recorder.stopNow()
|
||||
held = null
|
||||
}
|
||||
|
||||
private suspend fun png(bitmap: Bitmap): ByteArray = withContext(Dispatchers.Default) {
|
||||
@@ -473,19 +847,28 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
|
||||
companion object {
|
||||
const val MAX_SCREEN_CHARS = 8_000
|
||||
private const val NO_NOTIFICATIONS = "(none)"
|
||||
|
||||
// Listening, for the instance's speech-to-text (the phone's recogniser finds the end of
|
||||
// speech itself). Levels are the RMS of 16-bit samples, 0..1: a room is under 0.01,
|
||||
// a voice near the phone 0.02 and up. Not tuned on many phones: the stop button always works.
|
||||
private const val TICK_MS = 100L
|
||||
private const val SPEAKING = 0.02f
|
||||
private const val QUIET = 0.01f
|
||||
private const val PAUSE_MS = 1_800L
|
||||
private const val SAME_WORDS_MS = 4_500L
|
||||
private const val NOTHING_SAID_MS = 8_000L
|
||||
private const val LONGEST_MS = 120_000L
|
||||
/** How long, and how often, a new chat's name is asked for after its first reply. */
|
||||
private const val TITLE_WAIT_MS = 20_000L
|
||||
private const val TITLE_ASK_MS = 4_000L
|
||||
|
||||
// Listening: how often the end of speech is looked for (EndOfSpeech has the rules and
|
||||
// their numbers), and how often the recording so far is written down.
|
||||
private const val TICK_MS = EndOfSpeech.TICK_MS
|
||||
private const val PARTIAL_EVERY_MS = 1_200L
|
||||
|
||||
/**
|
||||
* The model a new assistant chat starts on: the one [chosen] in Settings while the
|
||||
* instance still has it; else ("Instance default", or a model that is gone) the
|
||||
* account's default, the instance's, or its first.
|
||||
*/
|
||||
fun assistantModelFor(chosen: String, accountDefault: String?, models: List<ModelInfo>): String? {
|
||||
// By ref, or -- a choice saved before refs, the account's default -- by id: either
|
||||
// way what comes back is the row's own unambiguous name.
|
||||
return (models.named(chosen) ?: models.named(accountDefault) ?: models.firstOrNull { it.default } ?: models.firstOrNull())?.key
|
||||
}
|
||||
|
||||
/** A reply's words, for a voice: its text steps, without the markup. */
|
||||
fun spokenWords(steps: List<Step>): String = plain(steps.filter { it.kind == "text" }.joinToString("\n\n") { it.markdown.orEmpty() })
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ fun AssistPanel(
|
||||
onOpenApp: () -> Unit,
|
||||
onNeedMic: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
onUnlock: () -> Unit = {},
|
||||
) {
|
||||
val state by controller.state.collectAsState()
|
||||
AssistSheetFrame(onDismiss = onDismiss) { handle, _ ->
|
||||
@@ -27,6 +28,7 @@ fun AssistPanel(
|
||||
locked = locked,
|
||||
handle = handle,
|
||||
onOpenApp = onOpenApp,
|
||||
onUnlock = onUnlock,
|
||||
onSend = { text -> if (locked) onUnlockAndAsk(text) else controller.ask(text) },
|
||||
onMic = {
|
||||
when {
|
||||
|
||||
@@ -2,14 +2,17 @@ package eu.llembas.android.assist
|
||||
|
||||
import android.app.KeyguardManager
|
||||
import android.app.assist.AssistStructure
|
||||
import android.app.role.RoleManager
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.service.voice.VoiceInteractionService
|
||||
import android.service.voice.VoiceInteractionSession
|
||||
import android.service.voice.VoiceInteractionSessionService
|
||||
import android.util.Log
|
||||
import android.view.View
|
||||
import android.view.WindowManager
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -25,13 +28,19 @@ import androidx.savedstate.SavedStateRegistryController
|
||||
import androidx.savedstate.SavedStateRegistryOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.SheetAtGate
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.wake.AssistLink
|
||||
import eu.llembas.android.wake.AssistPresence
|
||||
import eu.llembas.android.wake.wakeLogConnected
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
/**
|
||||
@@ -41,7 +50,81 @@ import kotlinx.coroutines.runBlocking
|
||||
* there is no hotword here -- Android keeps always-on hotword detection for the system's own
|
||||
* preinstalled assistant (`CAPTURE_AUDIO_HOTWORD` is a privileged permission).
|
||||
*/
|
||||
class LembasAssistService : VoiceInteractionService()
|
||||
class LembasAssistService : VoiceInteractionService() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
AssistLink.created(System.currentTimeMillis())
|
||||
}
|
||||
|
||||
override fun onReady() {
|
||||
super.onReady()
|
||||
current = this
|
||||
// When Android connected it is kept: the wake word's record says whether it was, and an
|
||||
// attempt that found it not connected is told that it came later.
|
||||
val now = System.currentTimeMillis()
|
||||
AssistLink.ready(now)
|
||||
Log.i(TAG, "assistant service connected by Android")
|
||||
background.launch { runCatching { lembas.instances.savePrefs { it.copy(wakeLog = wakeLogConnected(it.wakeLog, now)) } } }
|
||||
}
|
||||
|
||||
override fun onShutdown() {
|
||||
// Only the instance that is the current one disconnects it: an old one going away late
|
||||
// must not say "not connected" over a new one.
|
||||
if (current === this) {
|
||||
current = null
|
||||
AssistLink.shutdown(System.currentTimeMillis())
|
||||
}
|
||||
Log.i(TAG, "assistant service disconnected by Android")
|
||||
super.onShutdown()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
AssistLink.destroyed(System.currentTimeMillis())
|
||||
// With the service gone no sheet of it is up, whatever its session managed to say.
|
||||
lembas.gate.sessionHidden()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
/** Android 14+: Android is about to show a session it was asked for -- or, below, could not. Kept for the wake word's record. */
|
||||
override fun onPrepareToShowSession(args: Bundle, showFlags: Int) {
|
||||
AssistLink.prepared(SystemClock.elapsedRealtime())
|
||||
super.onPrepareToShowSession(args, showFlags)
|
||||
}
|
||||
|
||||
override fun onShowSessionFailed(args: Bundle) {
|
||||
AssistLink.showFailed(SystemClock.elapsedRealtime())
|
||||
Log.w(TAG, "Android could not show the assistant's session")
|
||||
super.onShowSessionFailed(args)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* The service while the system has it bound -- while LLeMbas is the phone's assistant. The
|
||||
* wake word opens the sheet through it ([showSession]), which Android allows from the
|
||||
* background, as it does for the power button.
|
||||
*/
|
||||
@Volatile
|
||||
var current: LembasAssistService? = null
|
||||
private set
|
||||
|
||||
private const val TAG = "LLeMbasWake"
|
||||
private val background = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
/**
|
||||
* Whether Android itself uses this service as its voice-interaction service right now.
|
||||
* Holding the assistant role is not the same: Android keeps the service only while a
|
||||
* speech recogniser is set that it accepts, and resets it at start-up otherwise -- the
|
||||
* long press then opens the assistant as an ordinary screen, and nothing is connected
|
||||
* that could open it from the background.
|
||||
*/
|
||||
fun isActive(context: Context): Boolean =
|
||||
runCatching { VoiceInteractionService.isActiveService(context, ComponentName(context, LembasAssistService::class.java)) }.getOrDefault(false)
|
||||
|
||||
/** Whether Android says LLeMbas holds the assistant role (Settings › Default apps › Digital assistant app). */
|
||||
fun holdsRole(context: Context): Boolean =
|
||||
runCatching { context.getSystemService(RoleManager::class.java)?.isRoleHeld(RoleManager.ROLE_ASSISTANT) }.getOrNull() ?: false
|
||||
}
|
||||
}
|
||||
|
||||
class LembasAssistSessionService : VoiceInteractionSessionService() {
|
||||
override fun onNewSession(args: Bundle?): VoiceInteractionSession = LembasAssistSession(this)
|
||||
@@ -61,6 +144,13 @@ class LembasAssistSession(context: Context) :
|
||||
private var controller = AssistController(context, scope)
|
||||
private val current = mutableStateOf(controller)
|
||||
|
||||
/** Whether this session's sheet is up, as far as the wake word's pause is concerned. */
|
||||
private var up = false
|
||||
private val atGate = SheetAtGate(context.lembas.gate)
|
||||
|
||||
/** Over the lock screen: waiting for what is heard, to hand it to the sheet's activity. */
|
||||
private var handing: Job? = null
|
||||
|
||||
override val lifecycle: Lifecycle get() = registry
|
||||
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
|
||||
|
||||
@@ -93,12 +183,12 @@ class LembasAssistSession(context: Context) :
|
||||
AssistPanel(
|
||||
controller = current.value,
|
||||
locked = locked(),
|
||||
onUnlockAndAsk = { text -> handOff(text) },
|
||||
onUnlockAndAsk = { text -> handOff(Held(text, null, spoken = false).takeIf { text.isNotBlank() }) },
|
||||
onOpenApp = {
|
||||
startAssistantActivity(current.value.appIntent())
|
||||
hide()
|
||||
},
|
||||
onNeedMic = { handOff("", listen = true) },
|
||||
onNeedMic = { handOff(null, listen = true) },
|
||||
onDismiss = { hide() },
|
||||
)
|
||||
}
|
||||
@@ -109,7 +199,31 @@ class LembasAssistSession(context: Context) :
|
||||
override fun onShow(args: Bundle?, showFlags: Int) {
|
||||
super.onShow(args, showFlags)
|
||||
registry.currentState = Lifecycle.State.RESUMED
|
||||
controller.opened(locked())
|
||||
// Android calls this again for a show asked for while the sheet is up, and hides once:
|
||||
// the sheet is counted as up once.
|
||||
if (!up) {
|
||||
up = true
|
||||
AssistPresence.shown()
|
||||
}
|
||||
// The sheet is the app in front: what it draws of the account (a reply's picture) may be
|
||||
// asked for, unless the phone is locked. Said each time; the gate keeps it as one.
|
||||
atGate.shown()
|
||||
AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
// One sheet, never two: a sheet the wake word opened as a screen of the app, because
|
||||
// this one was slow to come, goes now that this one is here.
|
||||
AssistActivity.closeWoken()
|
||||
// The wake word asks for the sheet listening, whatever Settings says about opening --
|
||||
// over the lock screen too, where what it hears is held and not asked.
|
||||
val showing = controller
|
||||
showing.opened(listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true)
|
||||
// A question that waits for the unlock (heard, or typed, over the lock screen) goes to
|
||||
// the sheet's activity, which can ask Android to unlock. Once: Android may call onShow
|
||||
// again while the sheet is up.
|
||||
handing?.cancel()
|
||||
handing = scope.launch {
|
||||
showing.state.first { it.held && locked() }
|
||||
showing.takeHeld()?.let { handOff(it) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -119,6 +233,11 @@ class LembasAssistSession(context: Context) :
|
||||
*/
|
||||
override fun onHide() {
|
||||
super.onHide()
|
||||
if (up) {
|
||||
up = false
|
||||
AssistPresence.hidden()
|
||||
}
|
||||
atGate.gone()
|
||||
controller.close()
|
||||
scope.cancel()
|
||||
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
@@ -129,6 +248,8 @@ class LembasAssistSession(context: Context) :
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
// A session torn down without being hidden must not leave the gate open behind it.
|
||||
atGate.gone()
|
||||
controller.close()
|
||||
scope.cancel()
|
||||
registry.currentState = Lifecycle.State.DESTROYED
|
||||
@@ -160,16 +281,12 @@ class LembasAssistSession(context: Context) :
|
||||
|
||||
/**
|
||||
* Over the lock screen nothing is sent from here: the question goes to [AssistActivity],
|
||||
* which asks Android to unlock first and only then sends it. The microphone's permission
|
||||
* which asks Android to unlock first and only then sends it. It is left in the app's own
|
||||
* memory ([AssistHandOff]) and the intent carries its ticket. The microphone's permission
|
||||
* prompt needs an activity too.
|
||||
*/
|
||||
private fun handOff(text: String, listen: Boolean = false) {
|
||||
startAssistantActivity(
|
||||
Intent(context, AssistActivity::class.java)
|
||||
.putExtra(AssistActivity.EXTRA_QUESTION, text)
|
||||
.putExtra(AssistActivity.EXTRA_LISTEN, listen)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
private fun handOff(question: Held?, listen: Boolean = false) {
|
||||
startAssistantActivity(AssistActivity.handedOver(context, question?.let { AssistHandOff.leave(it) }, listen))
|
||||
hide()
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import androidx.compose.foundation.gestures.Orientation
|
||||
import androidx.compose.foundation.gestures.draggable
|
||||
import androidx.compose.foundation.gestures.rememberDraggableState
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.interaction.DragInteraction
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -42,10 +43,13 @@ import androidx.compose.material.icons.automirrored.filled.VolumeOff
|
||||
import androidx.compose.material.icons.automirrored.filled.VolumeUp
|
||||
import androidx.compose.material.icons.filled.ArrowDropDown
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.Forum
|
||||
import androidx.compose.material.icons.filled.History
|
||||
import androidx.compose.material.icons.filled.Keyboard
|
||||
import androidx.compose.material.icons.filled.Lightbulb
|
||||
import androidx.compose.material.icons.filled.LockOpen
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.Notifications
|
||||
import androidx.compose.material.icons.filled.ScreenshotMonitor
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material.icons.filled.Summarize
|
||||
@@ -72,6 +76,7 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
@@ -87,9 +92,13 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.titleAmong
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.ProgressStatus
|
||||
import eu.llembas.android.ui.chat.PhoneCard
|
||||
import eu.llembas.android.ui.chat.Steps
|
||||
import eu.llembas.android.ui.chat.restFollows
|
||||
import eu.llembas.android.ui.chat.yielding
|
||||
import eu.llembas.android.ui.progressLineOf
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -194,7 +203,10 @@ fun AssistSheetFrame(onDismiss: () -> Unit, content: @Composable ColumnScope.(ha
|
||||
* - **the foot**: Use screen, then the microphone first -- while listening, the words as they are
|
||||
* heard and how loud -- or the words typed, and Send.
|
||||
*
|
||||
* Nothing from the account is on it while the phone is [locked]: no model list, no last chat.
|
||||
* Nothing from the account is on it while the phone is [locked]: no model list, no last chat,
|
||||
* no question asked earlier, no answer, no failure's words. A question heard over the lock
|
||||
* screen waits -- shown as the person's own words where the phone wrote them down, as "Question
|
||||
* heard" where it waits as a recording -- with the way to unlock, which sends it ([onUnlock]).
|
||||
*/
|
||||
@Composable
|
||||
fun ColumnScope.AssistSheetContent(
|
||||
@@ -203,14 +215,52 @@ fun ColumnScope.AssistSheetContent(
|
||||
locked: Boolean,
|
||||
handle: Modifier = Modifier,
|
||||
onOpenApp: () -> Unit = {},
|
||||
onUnlock: () -> Unit = {},
|
||||
onSend: (String) -> Unit = actions::ask,
|
||||
onMic: () -> Unit = actions::listen,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
var text by remember { mutableStateOf("") }
|
||||
val scroll = rememberScrollState()
|
||||
val growth = state.turns.lastOrNull()?.steps?.sumOf { (it.markdown?.length ?: 0) + (it.text?.length ?: 0) } ?: 0
|
||||
LaunchedEffect(state.turns.size, growth) { if (state.turns.isNotEmpty()) scroll.animateScrollTo(scroll.maxValue) }
|
||||
// The turns keep to their end while an answer is written only for a person who is there
|
||||
// (`ui/chat/Follow.kt`, the chat's rule): a finger on them ends the following, where they
|
||||
// come to rest says whether it is taken up again, and a question asked always shows.
|
||||
var following by remember { mutableStateOf(true) }
|
||||
val slack = with(LocalDensity.current) { 48.dp.roundToPx() }
|
||||
val touched = remember { booleanArrayOf(false) }
|
||||
LaunchedEffect(scroll) {
|
||||
scroll.interactionSource.interactions.collect {
|
||||
if (it is DragInteraction.Start) {
|
||||
touched[0] = true
|
||||
following = false
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(scroll) {
|
||||
var moving = false
|
||||
var from = scroll.value
|
||||
snapshotFlow { scroll.isScrollInProgress }.collect { now ->
|
||||
if (now && !moving) from = scroll.value
|
||||
if (moving && !now) {
|
||||
// Only the person's own scroll ends the following (`restFollows`), not one of ours
|
||||
// that an arriving line left short of the end.
|
||||
following = restFollows(following, touched[0] || scroll.value < from, scroll.maxValue - scroll.value, slack)
|
||||
touched[0] = false
|
||||
}
|
||||
moving = now
|
||||
}
|
||||
}
|
||||
LaunchedEffect(state.turns.size) { following = true }
|
||||
// The end moves when the answer grows and when the keyboard opens; before the first layout
|
||||
// it is not known yet.
|
||||
LaunchedEffect(scroll) {
|
||||
// Never against a finger: nothing is moved while a scroll is under way, and one of
|
||||
// ours that a finger interrupts does not end this follower (`yielding`). Whether a
|
||||
// scroll is under way is asked here and not watched: our own scroll is one too, and
|
||||
// watching it would have each scroll to the end start the next.
|
||||
snapshotFlow { if (following) scroll.maxValue else -1 }
|
||||
.collect { end -> if (end in 0 until Int.MAX_VALUE && !scroll.isScrollInProgress) yielding { scroll.scrollTo(end) } }
|
||||
}
|
||||
|
||||
// The top: the handle and the bar. Both drag the sheet.
|
||||
Column(handle.fillMaxWidth()) {
|
||||
@@ -264,18 +314,25 @@ fun ColumnScope.AssistSheetContent(
|
||||
Modifier.weight(1f).fillMaxWidth().verticalScroll(scroll).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
if (state.empty) {
|
||||
Starting(state, actions, locked)
|
||||
} else {
|
||||
state.turns.forEachIndexed { i, turn ->
|
||||
when {
|
||||
locked && state.held -> Waiting(state.waiting, onUnlock)
|
||||
|
||||
// A conversation that was on the sheet when the phone locked: not for the lock screen.
|
||||
locked && !state.empty -> Text(stringResource(R.string.assist_locked_line), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
|
||||
state.empty -> Starting(state, actions, locked)
|
||||
|
||||
else -> state.turns.forEachIndexed { i, turn ->
|
||||
Turn(turn, last = i == state.turns.lastIndex, state, actions, onOpenApp)
|
||||
}
|
||||
}
|
||||
state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
|
||||
// Not over the lock screen: a failure's words may name the instance.
|
||||
if (!locked) state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
|
||||
}
|
||||
|
||||
// The foot.
|
||||
Column(Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, top = 4.dp, bottom = 12.dp)) {
|
||||
if (state.conversation && !locked) Conversation(actions)
|
||||
if (state.screenAvailable && !locked) ScreenToggle(state, actions)
|
||||
if (state.listening) {
|
||||
Listening(state, onDone = actions::heard, onType = actions::type)
|
||||
@@ -384,15 +441,15 @@ private fun ModelChip(state: AssistUiState, actions: AssistActions) {
|
||||
state.models.forEach { model ->
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { ModelAvatar(model, model.id, size = 24.dp) },
|
||||
text = { Text(model.name.ifBlank { model.id }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
trailingIcon = if (model.id == state.modelId) {
|
||||
text = { Text(model.titleAmong(state.models), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
trailingIcon = if (model.key == state.modelInfo?.key) {
|
||||
{ Box(Modifier.size(8.dp).clip(CircleShape).background(palette.accent)) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
onClick = {
|
||||
open = false
|
||||
actions.pickModel(model.id)
|
||||
actions.pickModel(model.key)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -441,9 +498,13 @@ private fun Starting(state: AssistUiState, actions: AssistActions, locked: Boole
|
||||
QuickAction(Icons.Filled.Lightbulb, stringResource(R.string.assist_quick_explain)) { actions.quick(explain) }
|
||||
}
|
||||
}
|
||||
// The notifications, read only now that it is asked, and never over the lock screen.
|
||||
if (state.canReadNotifications && !locked) {
|
||||
QuickAction(Icons.Filled.Notifications, stringResource(R.string.assist_notifications)) { actions.summariseNotifications() }
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(stringResource(R.string.assist_help), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
Text(stringResource(R.string.assist_no_wake_word), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
Text(stringResource(R.string.assist_wake_word_hint), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -460,6 +521,41 @@ private fun QuickAction(icon: androidx.compose.ui.graphics.vector.ImageVector, l
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Over the lock screen: the question that was heard, as its bubble, and the one thing to do about
|
||||
* it. Unlocking sends it; nothing is sent and no answer shown before.
|
||||
*/
|
||||
@Composable
|
||||
private fun Waiting(question: String, onUnlock: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
// The words, where the phone itself wrote them down or they were typed; a question the
|
||||
// instance will write down waits as a recording, and there are no words to show yet.
|
||||
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) {
|
||||
Surface(color = palette.bubbleUser, contentColor = palette.ink, shape = RoundedCornerShape(20.dp), modifier = Modifier.widthIn(max = 300.dp)) {
|
||||
Text(
|
||||
question.ifBlank { stringResource(R.string.assist_question_heard) },
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(if (question.isBlank()) R.string.assist_recording_waits_line else R.string.assist_locked_line),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
)
|
||||
AssistChip(
|
||||
onClick = onUnlock,
|
||||
label = { Text(stringResource(R.string.assist_unlock_to_send)) },
|
||||
leadingIcon = { Icon(Icons.Filled.LockOpen, contentDescription = null, modifier = Modifier.size(18.dp)) },
|
||||
colors = AssistChipDefaults.assistChipColors(containerColor = palette.surfaceRaised, leadingIconContentColor = palette.accent),
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** One question, as a bubble on the right, and its answer at full width -- as in the app's chats. */
|
||||
@Composable
|
||||
private fun Turn(turn: AssistTurn, last: Boolean, state: AssistUiState, actions: AssistActions, onOpenApp: () -> Unit) {
|
||||
@@ -474,6 +570,11 @@ private fun Turn(turn: AssistTurn, last: Boolean, state: AssistUiState, actions:
|
||||
val reply = turn.reply
|
||||
val drawsProgress = reply != null && (progressLineOf(reply.progress) != null || reply.status.isNotBlank())
|
||||
when {
|
||||
// A phone action is confirmed here, where the phone is; any other card in the app.
|
||||
reply != null && reply.cards.any { it.kind == "phone_action" } -> reply.cards.first { it.kind == "phone_action" }.let { card ->
|
||||
PhoneCard(card) { answer -> actions.answerCard(card, answer) }
|
||||
}
|
||||
|
||||
reply != null && reply.cards.isNotEmpty() -> TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_answer_in_app)) }
|
||||
|
||||
turn.writing && drawsProgress -> ProgressStatus(reply?.progress, reply?.status.orEmpty(), MaterialTheme.typography.labelSmall, palette.inkFaint)
|
||||
@@ -498,6 +599,28 @@ private fun Turn(turn: AssistTurn, last: Boolean, state: AssistUiState, actions:
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A spoken conversation is on: the sheet will listen again after the answer is read. Says so,
|
||||
* and how it ends -- End here, "stop" said, or silence. The words give; End keeps its size.
|
||||
*/
|
||||
@Composable
|
||||
private fun Conversation(actions: AssistActions) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(shape = RoundedCornerShape(16.dp), color = palette.accentSoft, modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
|
||||
Row(Modifier.padding(start = 14.dp, end = 4.dp, top = 6.dp, bottom = 6.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Forum, contentDescription = null, tint = palette.accent, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.assist_conversation), style = MaterialTheme.typography.labelLarge, color = palette.accent)
|
||||
Text(stringResource(R.string.assist_conversation_line), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
TextButton(onClick = actions::endConversation, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.assist_conversation_end))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Use screen: off every time the sheet opens; on, the screen goes with the next question only. */
|
||||
@Composable
|
||||
private fun ScreenToggle(state: AssistUiState, actions: AssistActions) {
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
/**
|
||||
* When to stop listening, for the instance's speech-to-text (which takes a whole recording and
|
||||
* finds no end of speech itself). Fed the microphone's level once a tick ([tick]); apart from
|
||||
* Android, so it is tested with sequences of levels.
|
||||
*
|
||||
* Nothing here is an absolute loudness: a room's own noise differs from phone to phone by more
|
||||
* than a voice differs from a room. The **noise floor** is measured from the first sound on and
|
||||
* followed all the time -- the quietest level of the last two seconds, taken at once when it
|
||||
* falls and slowly, in calm moments, when it rises: the dips between words keep it down while
|
||||
* somebody speaks, and a steady noise (a fan, a car) becomes the floor within a moment. Speech and quiet are
|
||||
* levels relative to it:
|
||||
*
|
||||
* - **speech** begins when the level is well above the floor in [ONSET_TICKS] of the last
|
||||
* [ONSET_WINDOW] ticks -- a voice rises and falls, and one click or knock is not speech;
|
||||
* - listening may begin in the middle of a sentence (the wake word's shape: the person goes
|
||||
* straight on), and a voice that never dips far must not become "the room": the floor rises
|
||||
* only while the sound is calm, and sound that stays above the floor without being steady is
|
||||
* speech;
|
||||
* - once somebody spoke, a **pause** of [PAUSE_MS] back near the floor ends it ([Verdict.Said]);
|
||||
* - when **nothing is said**, it gives up after [NOTHING_SAID_MS] ([Verdict.Nothing]);
|
||||
* - the words written down so far are a second ear: the same words for [SAME_WORDS_MS] end it,
|
||||
* and words count as speech for a quiet voice -- but only when the microphone heard at least
|
||||
* something above the floor, because a speech-to-text model asked to write down silence
|
||||
* invents a sentence;
|
||||
* - and never longer than [LONGEST_MS].
|
||||
*/
|
||||
class EndOfSpeech(private val tickMs: Long = TICK_MS) {
|
||||
enum class Verdict { Listening, Said, Nothing }
|
||||
|
||||
/** The room's own level, as followed so far; 0 until the microphone gave any sound. */
|
||||
var floor = 0f
|
||||
private set
|
||||
|
||||
/** Whether somebody spoke. */
|
||||
var spoke = false
|
||||
private set
|
||||
|
||||
/**
|
||||
* Whether the microphone heard anything above the room at all: only then is the recording
|
||||
* worth writing down while it runs.
|
||||
*/
|
||||
val heardSomething: Boolean get() = spoke || stirred >= STIRRED_TICKS
|
||||
|
||||
private val recent = ArrayDeque<Float>()
|
||||
private var waited = 0L
|
||||
private val loud = ArrayDeque<Boolean>()
|
||||
private var stirred = 0
|
||||
private var aboveRun = 0
|
||||
|
||||
/** The floor is a guess: listening began in the middle of sound louder than any room is taken to be. */
|
||||
private var guessed = false
|
||||
private var overGuess = 0
|
||||
private var quietFor = 0L
|
||||
private var words = ""
|
||||
private var sameWordsFor = 0L
|
||||
|
||||
/** The level from which a sound is speech beginning, and the level under which it is a pause. */
|
||||
private fun speechFrom(): Float = maxOf(floor * SPEECH_RATIO, floor + SPEECH_MARGIN)
|
||||
|
||||
private fun pauseUnder(): Float = maxOf(floor * PAUSE_RATIO, floor + PAUSE_MARGIN)
|
||||
|
||||
/** One tick: the microphone's [level] (0..1, RMS) and the [heard] words written down so far. */
|
||||
fun tick(level: Float, heard: String = ""): Verdict {
|
||||
waited += tickMs
|
||||
// Exact zero before any sound is a microphone that has not given anything yet (or gives
|
||||
// nothing at all): it says nothing about the room. After sound it is silence -- a
|
||||
// headset that gates its noise gives exactly that between sentences -- and so a pause.
|
||||
if (level > 0f) {
|
||||
follow(level)
|
||||
} else if (floor > 0f) {
|
||||
judge(loud = false, above = false)
|
||||
}
|
||||
if (heard != words) {
|
||||
words = heard
|
||||
sameWordsFor = 0
|
||||
} else if (heard.isNotBlank()) {
|
||||
sameWordsFor += tickMs
|
||||
}
|
||||
if (heard.isNotBlank() && stirred >= STIRRED_TICKS) spoke = true
|
||||
return when {
|
||||
spoke && quietFor >= PAUSE_MS -> Verdict.Said
|
||||
spoke && sameWordsFor >= SAME_WORDS_MS -> Verdict.Said
|
||||
!spoke && waited >= NOTHING_SAID_MS -> Verdict.Nothing
|
||||
waited >= LONGEST_MS -> if (spoke) Verdict.Said else Verdict.Nothing
|
||||
else -> Verdict.Listening
|
||||
}
|
||||
}
|
||||
|
||||
private fun follow(level: Float) {
|
||||
recent.addLast(level)
|
||||
if (recent.size > WINDOW_TICKS) recent.removeFirst()
|
||||
val lowest = recent.min()
|
||||
// Steady over the whole window: a noise. Calm in the last half second: no voice now.
|
||||
val steady = recent.size >= CALM_TICKS && recent.max() <= lowest * STEADY_RATIO
|
||||
val last = recent.takeLast(CALM_TICKS)
|
||||
val calm = last.size >= CALM_TICKS && last.max() <= last.min() * STEADY_RATIO
|
||||
// The first sound is the room, unless somebody is already speaking -- then a guess,
|
||||
// until a dip or a calm moment shows the room. After it: down at once; up slowly, and
|
||||
// only while the sound is calm, so a voice does not lift the floor under itself.
|
||||
when {
|
||||
floor == 0f -> {
|
||||
floor = minOf(level, START_MAX)
|
||||
guessed = level > START_MAX
|
||||
}
|
||||
|
||||
lowest < floor -> {
|
||||
floor = lowest
|
||||
guessed = false
|
||||
}
|
||||
|
||||
calm -> {
|
||||
floor += (lowest - floor) * RISE
|
||||
guessed = false
|
||||
}
|
||||
}
|
||||
floor = floor.coerceAtLeast(MIN_FLOOR)
|
||||
judge(loud = level >= speechFrom(), above = level >= pauseUnder())
|
||||
// Sound that stays above the floor and is not steady is a voice: one that never dips
|
||||
// far, or -- while the floor is only a guess -- one that began before the listening did.
|
||||
overGuess = if (guessed && level > floor) overGuess + 1 else 0
|
||||
if ((aboveRun >= SUSTAINED_TICKS || overGuess >= SUSTAINED_TICKS) && !steady) spoke = true
|
||||
}
|
||||
|
||||
/** One tick's sound, judged: [loud] enough to be speech beginning, or at least [above] a pause. */
|
||||
private fun judge(loud: Boolean, above: Boolean) {
|
||||
this.loud.addLast(loud)
|
||||
if (this.loud.size > ONSET_WINDOW) this.loud.removeFirst()
|
||||
if (this.loud.count { it } >= ONSET_TICKS) spoke = true
|
||||
if (above) {
|
||||
stirred++
|
||||
aboveRun++
|
||||
quietFor = 0
|
||||
} else {
|
||||
aboveRun = 0
|
||||
quietFor += tickMs
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TICK_MS = 100L
|
||||
|
||||
/** How long the room's quietest level is looked for: two seconds. */
|
||||
private const val WINDOW_TICKS = 20
|
||||
|
||||
/** How fast the floor follows a room that got louder: a twentieth of the way each tick. */
|
||||
private const val RISE = 0.05f
|
||||
|
||||
/** No microphone is quieter than this; and the most the first sound may claim as "the room". */
|
||||
private const val MIN_FLOOR = 0.0008f
|
||||
private const val START_MAX = 0.02f
|
||||
|
||||
// Speech begins at a little over twice the floor (and at least a small step above it, for
|
||||
// a silent room); a pause is back within 1.6 times of it. Between the two nothing changes.
|
||||
private const val SPEECH_RATIO = 2.2f
|
||||
private const val SPEECH_MARGIN = 0.004f
|
||||
private const val PAUSE_RATIO = 1.6f
|
||||
private const val PAUSE_MARGIN = 0.002f
|
||||
private const val ONSET_TICKS = 3
|
||||
private const val ONSET_WINDOW = 8
|
||||
private const val STIRRED_TICKS = 4
|
||||
|
||||
// Steady, calm: the loudest within half again of the quietest -- over the window, over
|
||||
// the last half second. Sustained: above the floor for a second without a break.
|
||||
private const val CALM_TICKS = 5
|
||||
private const val STEADY_RATIO = 1.5f
|
||||
private const val SUSTAINED_TICKS = 10
|
||||
|
||||
const val PAUSE_MS = 1_500L
|
||||
const val SAME_WORDS_MS = 4_500L
|
||||
const val NOTHING_SAID_MS = 5_000L
|
||||
const val LONGEST_MS = 60_000L
|
||||
}
|
||||
}
|
||||
|
||||
/** What to do about the phone's own recogniser, which finds the end of speech itself -- usually. */
|
||||
enum class PhoneWatch {
|
||||
Wait,
|
||||
|
||||
/** Ask it to stop and give what it has. */
|
||||
Finish,
|
||||
|
||||
/** It did not answer the asking either: take the words it showed. */
|
||||
Take,
|
||||
|
||||
/** Nothing was said, and it has not said so itself. */
|
||||
GiveUp,
|
||||
}
|
||||
|
||||
/**
|
||||
* The watch kept over the phone's recogniser, from how long it has listened ([waitedMs]), whether
|
||||
* it has shown any words ([anyWords]), for how long they have stayed the same ([sameForMs]), and
|
||||
* how long ago it last gave a sign of somebody speaking ([silentForMs]: its "speech began", a
|
||||
* loud level, new words -- not every recogniser shows words while one speaks).
|
||||
* A recogniser normally ends by itself; some never call back, and the sheet would listen for good.
|
||||
* No words and nothing heard for a while gives up; when somebody did speak before that quiet, it
|
||||
* is first asked for what it has.
|
||||
*/
|
||||
fun phoneWatch(waitedMs: Long, anyWords: Boolean, sameForMs: Long, silentForMs: Long = waitedMs): PhoneWatch = when {
|
||||
waitedMs >= EndOfSpeech.LONGEST_MS + PHONE_GRACE_MS -> if (anyWords) PhoneWatch.Take else PhoneWatch.GiveUp
|
||||
waitedMs >= EndOfSpeech.LONGEST_MS -> PhoneWatch.Finish
|
||||
!anyWords && silentForMs >= PHONE_NOTHING_SAID_MS + PHONE_GRACE_MS -> PhoneWatch.GiveUp
|
||||
!anyWords && silentForMs >= PHONE_NOTHING_SAID_MS -> if (silentForMs < waitedMs) PhoneWatch.Finish else PhoneWatch.GiveUp
|
||||
anyWords && sameForMs >= EndOfSpeech.SAME_WORDS_MS + PHONE_GRACE_MS -> PhoneWatch.Take
|
||||
anyWords && sameForMs >= EndOfSpeech.SAME_WORDS_MS && silentForMs >= EndOfSpeech.PAUSE_MS -> PhoneWatch.Finish
|
||||
else -> PhoneWatch.Wait
|
||||
}
|
||||
|
||||
/** Longer than the recogniser's own "no speech" (about five seconds on most): it gets to say so first. */
|
||||
const val PHONE_NOTHING_SAID_MS = 8_000L
|
||||
|
||||
/** How long a recogniser that was asked to stop has to answer. */
|
||||
const val PHONE_GRACE_MS = 2_500L
|
||||
@@ -1,11 +1,17 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.speech.RecognitionListener
|
||||
import android.speech.RecognitionService
|
||||
import android.speech.RecognizerIntent
|
||||
import android.speech.SpeechRecognizer
|
||||
import androidx.annotation.RequiresApi
|
||||
import eu.llembas.android.api.MediaFor
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -15,11 +21,39 @@ import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Who writes down what an app asked the system's recogniser to hear. */
|
||||
enum class Recognise {
|
||||
/** The instance's speech-to-text: the recording is sent to it. */
|
||||
Instance,
|
||||
|
||||
/** The phone's on-device recogniser: nothing leaves the phone through LLeMbas. */
|
||||
OnDevice,
|
||||
|
||||
/** Nobody: the calling app is told there is no recogniser for it now. */
|
||||
Refuse,
|
||||
}
|
||||
|
||||
/**
|
||||
* The lock-screen rule for the system recogniser: nothing goes to the instance while the phone
|
||||
* is [locked], whoever asks. Locked, the on-device recogniser hears it where the phone has one
|
||||
* ([onDevice]); a phone without one answers the app that it cannot.
|
||||
*/
|
||||
fun recogniseWith(locked: Boolean, onDevice: Boolean): Recognise = when {
|
||||
!locked -> Recognise.Instance
|
||||
onDevice -> Recognise.OnDevice
|
||||
else -> Recognise.Refuse
|
||||
}
|
||||
|
||||
/**
|
||||
* Speech recognition through the instance (`/v1/audio/transcriptions`). Android requires a
|
||||
* digital assistant to name a recognition service; this is it, and any app that asks the
|
||||
* system's recognizer while LLeMbas is the assistant is answered by the instance's
|
||||
* speech-to-text. Listening ends when the caller says stop, or after [LIMIT_MS].
|
||||
* speech-to-text. Listening ends when the caller says stop, at a pause after speech or when
|
||||
* nothing is said ([EndOfSpeech], as in the assistant's sheet), or after [LIMIT_MS].
|
||||
*
|
||||
* Not while the phone is locked ([recogniseWith]): an app over the lock screen gets the phone's
|
||||
* on-device recogniser, or [UNAVAILABLE]. A phone that locks while a recording is being made
|
||||
* sends nothing either.
|
||||
*/
|
||||
class LembasRecognitionService : RecognitionService() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
@@ -27,31 +61,133 @@ class LembasRecognitionService : RecognitionService() {
|
||||
private var callback: RecognitionService.Callback? = null
|
||||
private var limit: Job? = null
|
||||
|
||||
/** The on-device recogniser hearing a locked phone's request, while it does. */
|
||||
private var phone: SpeechRecognizer? = null
|
||||
|
||||
private fun locked(): Boolean = getSystemService(KeyguardManager::class.java)?.isKeyguardLocked == true
|
||||
|
||||
private fun onDevice(): Boolean = Build.VERSION.SDK_INT >= 31 && SpeechRecognizer.isOnDeviceRecognitionAvailable(this)
|
||||
|
||||
override fun onStartListening(intent: Intent?, listener: RecognitionService.Callback) {
|
||||
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||
listener.error(SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS)
|
||||
return
|
||||
}
|
||||
dropPhone()
|
||||
when (recogniseWith(locked(), onDevice())) {
|
||||
Recognise.Instance -> Unit
|
||||
|
||||
Recognise.OnDevice -> {
|
||||
if (Build.VERSION.SDK_INT >= 31) listenOnDevice(intent, listener)
|
||||
return
|
||||
}
|
||||
|
||||
Recognise.Refuse -> {
|
||||
listener.error(UNAVAILABLE)
|
||||
return
|
||||
}
|
||||
}
|
||||
callback = listener
|
||||
recorder.start()
|
||||
listener.readyForSpeech(Bundle())
|
||||
listener.beginningOfSpeech()
|
||||
limit = scope.launch {
|
||||
delay(LIMIT_MS)
|
||||
val ear = EndOfSpeech()
|
||||
var waited = 0L
|
||||
while (waited < LIMIT_MS) {
|
||||
delay(EndOfSpeech.TICK_MS)
|
||||
waited += EndOfSpeech.TICK_MS
|
||||
when (ear.tick(recorder.level.value)) {
|
||||
EndOfSpeech.Verdict.Said -> break
|
||||
|
||||
// Nothing said is nothing sent: silence written down is an invented sentence.
|
||||
EndOfSpeech.Verdict.Nothing -> {
|
||||
silent()
|
||||
return@launch
|
||||
}
|
||||
|
||||
EndOfSpeech.Verdict.Listening -> Unit
|
||||
}
|
||||
}
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone's on-device recogniser in LLeMbas's place: what it hears and says goes to the
|
||||
* calling app as it is. Never the system's default recogniser, which is this service.
|
||||
*/
|
||||
@RequiresApi(31)
|
||||
private fun listenOnDevice(intent: Intent?, listener: RecognitionService.Callback) {
|
||||
val made = SpeechRecognizer.createOnDeviceSpeechRecognizer(this)
|
||||
phone = made
|
||||
// The calling app may be gone by the time a word comes: nobody is left to tell.
|
||||
fun tell(say: () -> Unit) {
|
||||
runCatching(say)
|
||||
}
|
||||
made.setRecognitionListener(
|
||||
object : RecognitionListener {
|
||||
override fun onReadyForSpeech(params: Bundle?) = tell { listener.readyForSpeech(params ?: Bundle()) }
|
||||
|
||||
override fun onBeginningOfSpeech() = tell { listener.beginningOfSpeech() }
|
||||
|
||||
override fun onRmsChanged(rmsdB: Float) = tell { listener.rmsChanged(rmsdB) }
|
||||
|
||||
override fun onBufferReceived(buffer: ByteArray?) {}
|
||||
|
||||
override fun onEndOfSpeech() = tell { listener.endOfSpeech() }
|
||||
|
||||
override fun onError(error: Int) {
|
||||
dropPhone()
|
||||
tell { listener.error(error) }
|
||||
}
|
||||
|
||||
override fun onResults(results: Bundle?) {
|
||||
dropPhone()
|
||||
tell { listener.results(results ?: Bundle()) }
|
||||
}
|
||||
|
||||
override fun onPartialResults(partialResults: Bundle?) = tell { listener.partialResults(partialResults ?: Bundle()) }
|
||||
|
||||
override fun onEvent(eventType: Int, params: Bundle?) {}
|
||||
},
|
||||
)
|
||||
made.startListening(intent?.let { Intent(it) } ?: Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH))
|
||||
}
|
||||
|
||||
private fun dropPhone() {
|
||||
phone?.runCatching {
|
||||
cancel()
|
||||
destroy()
|
||||
}
|
||||
phone = null
|
||||
}
|
||||
|
||||
override fun onStopListening(listener: RecognitionService.Callback) {
|
||||
phone?.let {
|
||||
it.stopListening()
|
||||
return
|
||||
}
|
||||
finish()
|
||||
}
|
||||
|
||||
override fun onCancel(listener: RecognitionService.Callback) {
|
||||
dropPhone()
|
||||
limit?.cancel()
|
||||
callback = null
|
||||
scope.launch { recorder.stop() }
|
||||
}
|
||||
|
||||
/** Nobody spoke: the caller is told so, and nothing is written down. */
|
||||
private fun silent() {
|
||||
val listener = callback ?: return
|
||||
callback = null
|
||||
scope.launch {
|
||||
recorder.stop()
|
||||
listener.error(SpeechRecognizer.ERROR_SPEECH_TIMEOUT)
|
||||
}
|
||||
}
|
||||
|
||||
private fun finish() {
|
||||
val listener = callback ?: return
|
||||
callback = null
|
||||
@@ -59,8 +195,14 @@ class LembasRecognitionService : RecognitionService() {
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
listener.endOfSpeech()
|
||||
// The phone locked while it listened: the recording goes nowhere.
|
||||
if (locked()) {
|
||||
listener.error(UNAVAILABLE)
|
||||
return@launch
|
||||
}
|
||||
try {
|
||||
val text = lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
// Another app's dictation belongs to no chat: the instance's default writes it down.
|
||||
val text = lembas.instances.client()?.transcribe(wav, media = MediaFor.DEFAULT)?.text.orEmpty()
|
||||
if (text.isBlank()) {
|
||||
listener.error(SpeechRecognizer.ERROR_NO_MATCH)
|
||||
} else {
|
||||
@@ -73,11 +215,19 @@ class LembasRecognitionService : RecognitionService() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
dropPhone()
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val LIMIT_MS = 15_000L
|
||||
|
||||
/**
|
||||
* What a calling app is told when nothing may hear it now: the recogniser is busy, which
|
||||
* is the error an app takes as "not now, try again" rather than as its own mistake or a
|
||||
* missing permission.
|
||||
*/
|
||||
const val UNAVAILABLE = SpeechRecognizer.ERROR_RECOGNIZER_BUSY
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* Telling the app's own intents from anybody's. [AssistActivity] is exported -- Android's
|
||||
* `ACTION_ASSIST` and a headset's voice button must reach it -- so any app can start it with any
|
||||
* action and any extras. What only the app's own parts may ask for (open listening, continue the
|
||||
* last chat, turn the screen on, take a handed-over question) is therefore honoured only on an
|
||||
* intent that carries the app's own mark: a random value made once on this phone and kept in the
|
||||
* app's private storage. The widget's and the shortcuts' intents carry it inside a
|
||||
* `PendingIntent` or a shortcut, which no other app can read.
|
||||
*/
|
||||
object OwnIntents {
|
||||
private const val STORE = "own_intents"
|
||||
private const val KEY = "mark"
|
||||
private const val EXTRA_MARK = "eu.llembas.android.OWN"
|
||||
|
||||
@Volatile
|
||||
private var cached: String? = null
|
||||
|
||||
private fun mark(context: Context): String = cached ?: synchronized(this) {
|
||||
cached ?: run {
|
||||
val store = context.applicationContext.getSharedPreferences(STORE, Context.MODE_PRIVATE)
|
||||
val kept = store.getString(KEY, null) ?: newMark().also { store.edit().putString(KEY, it).apply() }
|
||||
cached = kept
|
||||
kept
|
||||
}
|
||||
}
|
||||
|
||||
private fun newMark(): String = ByteArray(24).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
|
||||
|
||||
/** [intent], marked as the app's own. */
|
||||
fun own(context: Context, intent: Intent): Intent = intent.putExtra(EXTRA_MARK, mark(context))
|
||||
|
||||
/** Whether [intent] was made by the app itself. */
|
||||
fun isOwn(context: Context, intent: Intent?): Boolean = sameMark(runCatching { intent?.getStringExtra(EXTRA_MARK) }.getOrNull(), mark(context))
|
||||
|
||||
/** Compared in full, whatever differs: how long it takes says nothing about where. */
|
||||
internal fun sameMark(given: String?, kept: String): Boolean {
|
||||
if (given == null || given.length != kept.length) return false
|
||||
var differs = 0
|
||||
for (i in kept.indices) differs = differs or (given[i].code xor kept[i].code)
|
||||
return differs == 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A question on its way from one sheet to the other -- the assistant's own sheet hands what was
|
||||
* typed or heard over the lock screen to [AssistActivity], which can ask Android to unlock. It
|
||||
* never travels in the intent: an intent's extras are whatever its sender says, and a question
|
||||
* found there would be asked on the account for any app that put it there. The question waits
|
||||
* here, in the app's own memory; the intent carries only the ticket, good once.
|
||||
*/
|
||||
object AssistHandOff {
|
||||
private var ticket: String? = null
|
||||
private var waiting: Held? = null
|
||||
|
||||
/** Leave [question] here; the ticket to put on the intent. */
|
||||
@Synchronized
|
||||
fun leave(question: Held): String {
|
||||
val made = ByteArray(16).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
|
||||
ticket = made
|
||||
waiting = question
|
||||
return made
|
||||
}
|
||||
|
||||
/** The question left under [given], once; nothing for any other ticket, or none. */
|
||||
@Synchronized
|
||||
fun take(given: String?): Held? {
|
||||
val kept = ticket ?: return null
|
||||
if (given == null || !OwnIntents.sameMark(given, kept)) return null
|
||||
val question = waiting
|
||||
ticket = null
|
||||
waiting = null
|
||||
return question
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,9 @@ import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioDeviceInfo
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioManager
|
||||
import android.media.AudioRecord
|
||||
import android.media.MediaPlayer
|
||||
import android.media.MediaRecorder
|
||||
@@ -17,6 +19,7 @@ import android.speech.RecognizerIntent
|
||||
import android.speech.SpeechRecognizer
|
||||
import androidx.annotation.RequiresPermission
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
@@ -56,6 +59,9 @@ class Recorder(private val scope: CoroutineScope) {
|
||||
/** How many seconds have been recorded. */
|
||||
val seconds: Float get() = pcm.size() / (RATE * 2f)
|
||||
|
||||
/** The microphone to prefer -- a headset's, while one is the route ([HeadsetRoute]). */
|
||||
var preferred: AudioDeviceInfo? = null
|
||||
|
||||
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
|
||||
fun start() {
|
||||
if (record != null) return
|
||||
@@ -69,6 +75,7 @@ class Recorder(private val scope: CoroutineScope) {
|
||||
maxOf(min, RATE),
|
||||
)
|
||||
record = audio
|
||||
preferred?.let { audio.setPreferredDevice(it) }
|
||||
audio.startRecording()
|
||||
job = scope.launch(Dispatchers.IO) {
|
||||
val buffer = ByteArray(maxOf(min, 4096))
|
||||
@@ -100,6 +107,22 @@ class Recorder(private val scope: CoroutineScope) {
|
||||
return if (body.isEmpty()) body else wav(body)
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop and keep nothing, at once and without a coroutine: for when the scope that would
|
||||
* run [stop] is already cancelled (the sheet is going), and the microphone must still be
|
||||
* let go.
|
||||
*/
|
||||
fun stopNow() {
|
||||
val audio = record ?: return
|
||||
record = null
|
||||
job?.cancel()
|
||||
// Stop returns the blocked `read`; the loop then sees it is cancelled, or reads an error.
|
||||
runCatching { audio.stop() }
|
||||
runCatching { audio.release() }
|
||||
_level.value = 0f
|
||||
pcm.reset()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val RATE = 16_000
|
||||
private const val MAX_BYTES = RATE * 2 * 120 // two minutes
|
||||
@@ -143,11 +166,15 @@ class Speaker(private val context: Context) {
|
||||
private val _playing = MutableStateFlow(false)
|
||||
val playing: StateFlow<Boolean> = _playing.asStateFlow()
|
||||
|
||||
private var ended: CompletableDeferred<Boolean>? = null
|
||||
|
||||
suspend fun play(mp3: ByteArray) {
|
||||
stop()
|
||||
val file = withContext(Dispatchers.IO) {
|
||||
File.createTempFile("reply", ".mp3", context.cacheDir).apply { writeBytes(mp3) }
|
||||
}
|
||||
val done = CompletableDeferred<Boolean>()
|
||||
ended = done
|
||||
player = MediaPlayer().apply {
|
||||
setAudioAttributes(
|
||||
AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ASSISTANT)
|
||||
@@ -159,6 +186,7 @@ class Speaker(private val context: Context) {
|
||||
file.delete()
|
||||
player = null
|
||||
_playing.value = false
|
||||
done.complete(true)
|
||||
}
|
||||
prepare()
|
||||
start()
|
||||
@@ -166,6 +194,12 @@ class Speaker(private val context: Context) {
|
||||
_playing.value = true
|
||||
}
|
||||
|
||||
/** Play [mp3] and wait: true when it was heard to the end, false when it was stopped. */
|
||||
suspend fun playToEnd(mp3: ByteArray): Boolean {
|
||||
play(mp3)
|
||||
return ended?.await() ?: false
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
player?.runCatching {
|
||||
stop()
|
||||
@@ -173,9 +207,58 @@ class Speaker(private val context: Context) {
|
||||
}
|
||||
player = null
|
||||
_playing.value = false
|
||||
ended?.complete(false)
|
||||
ended = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A headset's microphone for the assistant, while one is connected: a Bluetooth headset is
|
||||
* made the communication device (Android 12+), so the sheet hears the headset and answers into
|
||||
* it, as a call would; a wired headset's microphone is the default anyway. [release] gives the
|
||||
* route back. Nothing happens without a headset.
|
||||
*/
|
||||
class HeadsetRoute(context: Context) {
|
||||
private val audio = context.getSystemService(AudioManager::class.java)
|
||||
private var engaged = false
|
||||
|
||||
/** The headset's microphone, if there is one -- made the route first where that is needed. */
|
||||
fun microphone(): AudioDeviceInfo? {
|
||||
val inputs = audio?.getDevices(AudioManager.GET_DEVICES_INPUTS).orEmpty()
|
||||
val wired = inputs.firstOrNull { it.type == AudioDeviceInfo.TYPE_WIRED_HEADSET || it.type == AudioDeviceInfo.TYPE_USB_HEADSET }
|
||||
if (wired != null) return wired
|
||||
if (Build.VERSION.SDK_INT < 31 || audio == null) return null
|
||||
val headset = audio.availableCommunicationDevices.firstOrNull {
|
||||
it.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO || it.type == AudioDeviceInfo.TYPE_BLE_HEADSET
|
||||
} ?: return null
|
||||
if (!engaged) engaged = runCatching { audio.setCommunicationDevice(headset) }.getOrDefault(false)
|
||||
return inputs.firstOrNull { it.type == headset.type } ?: headset
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (engaged && Build.VERSION.SDK_INT >= 31) runCatching { audio?.clearCommunicationDevice() }
|
||||
engaged = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [heard] is the person ending a spoken conversation: one of [phrases] ("stop", "that's
|
||||
* all", in the app's language), alone or with a word or two around it ("stop please", "ok
|
||||
* that's all"). A longer sentence that happens to hold "stop" is a question, not an ending.
|
||||
*/
|
||||
fun isStopPhrase(heard: String, phrases: List<String>): Boolean {
|
||||
val said = words(heard)
|
||||
if (said.isEmpty()) return false
|
||||
return phrases.map(::words).filter { it.isNotEmpty() }.any { phrase ->
|
||||
said.size <= phrase.size + 2 && said.windowed(phrase.size).any { it == phrase }
|
||||
}
|
||||
}
|
||||
|
||||
private fun words(text: String): List<String> = text.lowercase()
|
||||
.replace(Regex("[\\u2019']"), "")
|
||||
.split(Regex("[^\\p{L}\\p{N}]+"))
|
||||
.filter { it.isNotBlank() }
|
||||
|
||||
/**
|
||||
* Speech in through the phone's own recogniser, for Settings › Voice input › Phone: words as
|
||||
* they are said ([start]'s `onPartial`), and the end of speech found by the recogniser.
|
||||
@@ -188,53 +271,66 @@ class Speaker(private val context: Context) {
|
||||
class PhoneRecognizer(private val context: Context) {
|
||||
private var recognizer: SpeechRecognizer? = null
|
||||
|
||||
fun start(onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit) {
|
||||
/** [onActive]: a sign that somebody is speaking -- "speech began", or a loud level -- for a recogniser that shows no words meanwhile. */
|
||||
fun start(onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit, onActive: () -> Unit = {}) {
|
||||
stop()
|
||||
startWith(onDevice(context), onPartial, onLevel, onResult, onFail)
|
||||
startWith(onDevice(context), Heard(onPartial, onLevel, onResult, onFail, onActive))
|
||||
}
|
||||
|
||||
private class Heard(
|
||||
val onPartial: (String) -> Unit,
|
||||
val onLevel: (Float) -> Unit,
|
||||
val onResult: (String) -> Unit,
|
||||
val onFail: (Int) -> Unit,
|
||||
val onActive: () -> Unit,
|
||||
)
|
||||
|
||||
// `onFail`, not `onError`: inside the listener below that name is the listener's own method.
|
||||
private fun startWith(onDevice: Boolean, onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit) {
|
||||
private fun startWith(onDevice: Boolean, to: Heard) {
|
||||
val other = component(context)
|
||||
val made = when {
|
||||
onDevice && Build.VERSION.SDK_INT >= 31 -> SpeechRecognizer.createOnDeviceSpeechRecognizer(context)
|
||||
other != null -> SpeechRecognizer.createSpeechRecognizer(context, other)
|
||||
else -> return onFail(SpeechRecognizer.ERROR_CLIENT)
|
||||
else -> return to.onFail(SpeechRecognizer.ERROR_CLIENT)
|
||||
}
|
||||
recognizer = made
|
||||
made.setRecognitionListener(
|
||||
object : RecognitionListener {
|
||||
override fun onReadyForSpeech(params: Bundle?) {}
|
||||
|
||||
override fun onBeginningOfSpeech() {}
|
||||
override fun onBeginningOfSpeech() = to.onActive()
|
||||
|
||||
// About -2 dB in silence to 10 dB speaking: the meter's 0..1.
|
||||
override fun onRmsChanged(rmsdB: Float) = onLevel(((rmsdB + 2f) / 12f).coerceIn(0f, 1f))
|
||||
override fun onRmsChanged(rmsdB: Float) {
|
||||
val level = ((rmsdB + 2f) / 12f).coerceIn(0f, 1f)
|
||||
to.onLevel(level)
|
||||
if (level >= LOUD) to.onActive()
|
||||
}
|
||||
|
||||
override fun onBufferReceived(buffer: ByteArray?) {}
|
||||
|
||||
override fun onEndOfSpeech() = onLevel(0f)
|
||||
override fun onEndOfSpeech() = to.onLevel(0f)
|
||||
|
||||
override fun onError(error: Int) {
|
||||
// The on-device recogniser lacks this language: another app's may have it.
|
||||
if (onDevice && other != null && (error == LANGUAGE_NOT_SUPPORTED || error == LANGUAGE_UNAVAILABLE)) {
|
||||
stop()
|
||||
startWith(false, onPartial, onLevel, onResult, onFail)
|
||||
startWith(false, to)
|
||||
return
|
||||
}
|
||||
stop()
|
||||
onFail(error)
|
||||
to.onFail(error)
|
||||
}
|
||||
|
||||
override fun onResults(results: Bundle?) {
|
||||
val text = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull().orEmpty()
|
||||
stop()
|
||||
onResult(text)
|
||||
to.onResult(text)
|
||||
}
|
||||
|
||||
override fun onPartialResults(partialResults: Bundle?) {
|
||||
partialResults?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()
|
||||
?.takeIf { it.isNotBlank() }?.let(onPartial)
|
||||
?.takeIf { it.isNotBlank() }?.let(to.onPartial)
|
||||
}
|
||||
|
||||
override fun onEvent(eventType: Int, params: Bundle?) {}
|
||||
@@ -244,6 +340,10 @@ class PhoneRecognizer(private val context: Context) {
|
||||
Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
|
||||
.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
|
||||
.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
|
||||
// How long a silence ends it: a hint, which not every recogniser takes -- the
|
||||
// sheet keeps its own watch as well (phoneWatch).
|
||||
.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, EndOfSpeech.PAUSE_MS)
|
||||
.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, EndOfSpeech.PAUSE_MS)
|
||||
.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.packageName),
|
||||
)
|
||||
}
|
||||
@@ -266,6 +366,9 @@ class PhoneRecognizer(private val context: Context) {
|
||||
private const val LANGUAGE_NOT_SUPPORTED = 12
|
||||
private const val LANGUAGE_UNAVAILABLE = 13
|
||||
|
||||
/** Half of the meter: a level that is a voice, not a room. */
|
||||
private const val LOUD = 0.5f
|
||||
|
||||
private fun onDevice(context: Context): Boolean = Build.VERSION.SDK_INT >= 31 && SpeechRecognizer.isOnDeviceRecognitionAvailable(context)
|
||||
|
||||
/** Another app's recogniser -- never LLeMbas's own, which would send it back to the instance. */
|
||||
|
||||
@@ -9,6 +9,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.wake.WakeAttempt
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
@@ -85,6 +86,24 @@ data class Prefs(
|
||||
val accountLanguage: String = "",
|
||||
val voiceInput: String = VOICE_LEMBAS,
|
||||
val assistantListens: Boolean = true,
|
||||
/** After a spoken answer is read aloud, listen again: a spoken conversation. */
|
||||
val assistantConversation: Boolean = true,
|
||||
/** Listen for a wake word on the phone (WakeWordService). Off until the person turns it on. */
|
||||
val wakeWord: Boolean = false,
|
||||
/** Which of WakePhrases.all, as `greeting_name`; an id that is no phrase any more reads as the default. */
|
||||
val wakePhrase: String = "hey_assistant",
|
||||
/** WakeSensitivity's id: low, normal or high. */
|
||||
val wakeSensitivity: String = "normal",
|
||||
/** What happened the last times the wake word was heard (WakeLog): shown in Settings, nothing of the account in it. */
|
||||
val wakeLog: List<WakeAttempt> = emptyList(),
|
||||
/** Listen only while the screen is on. */
|
||||
val wakeScreenOnly: Boolean = true,
|
||||
/** The assistant may read the notifications when asked (with Android's notification access). */
|
||||
val notificationSummaries: Boolean = false,
|
||||
/** Phone actions' navigation app: "" whichever is installed, "google", "osmand", or "ask". */
|
||||
val navApp: String = "",
|
||||
/** Ask OsmAnd for the phone's position and the route's destination (allowed inside OsmAnd first). */
|
||||
val osmandInfo: Boolean = false,
|
||||
val assistantModel: String = "",
|
||||
val lastAssistChat: String = "",
|
||||
val lastAssistTitle: String = "",
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package eu.llembas.android.notify
|
||||
|
||||
/** One notification, as the question carries it. */
|
||||
data class Notice(val app: String, val title: String, val text: String, val at: Long)
|
||||
|
||||
/**
|
||||
* Notification summaries, the half every build has: how the notifications are written into a
|
||||
* question, and when a question asks for them. Reading them is [NotificationAccess]'s, which only
|
||||
* the `notifications` build can do.
|
||||
*/
|
||||
object NotificationReader {
|
||||
/** The notifications as the question's attachment of text: one block per notification. */
|
||||
fun asText(notices: List<Notice>, now: Long = System.currentTimeMillis()): String = notices.joinToString("\n\n") { n ->
|
||||
val minutes = ((now - n.at) / 60_000).coerceAtLeast(0)
|
||||
val ago = if (minutes < 60) "${minutes}m ago" else "${minutes / 60}h ago"
|
||||
listOf("[${n.app} · $ago] ${n.title}".trim(), n.text).filter { it.isNotBlank() }.joinToString("\n")
|
||||
}.take(MAX_CHARS)
|
||||
|
||||
/**
|
||||
* Whether a question asks about the notifications: one of [phrases] (in the app's language,
|
||||
* "my notifications" and the like) is in it.
|
||||
*/
|
||||
fun asksAbout(question: String, phrases: List<String>): Boolean {
|
||||
val q = question.lowercase()
|
||||
return phrases.map { it.trim().lowercase() }.any { it.isNotEmpty() && it in q }
|
||||
}
|
||||
|
||||
private const val MAX_CHARS = 12_000
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import eu.llembas.android.R
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.PushPayload
|
||||
import eu.llembas.android.api.safeId
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
@@ -100,11 +101,18 @@ object Notifications {
|
||||
|
||||
const val EXTRA_SCHEDULE = "eu.llembas.android.SCHEDULE"
|
||||
const val EXTRA_RUN = "eu.llembas.android.RUN"
|
||||
const val EXTRA_REPORT = "eu.llembas.android.REPORT"
|
||||
|
||||
/** Whether [kind] is about a chat: a finished reply (which older payloads leave unnamed) or a question or an approval. */
|
||||
fun chatKind(kind: String): Boolean = kind == "" || kind == "reply" || kind == "ask"
|
||||
|
||||
fun show(context: Context, instance: String, payload: PushPayload) {
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return
|
||||
if (payload.kind == "schedule" || payload.kind == "schedule_failed") return scheduled(context, instance, payload)
|
||||
val chatId = payload.chatId ?: payload.url.removePrefix("/chat/").takeIf { payload.url.startsWith("/chat/") }
|
||||
if (payload.kind == ReportNotice.KIND) return report(context, instance, payload)
|
||||
// A kind this app does not know -- a newer server's -- is not guessed at: no notification.
|
||||
if (!chatKind(payload.kind)) return
|
||||
val chatId = safeId(payload.chatId ?: payload.url.removePrefix("/chat/").takeIf { payload.url.startsWith("/chat/") })
|
||||
val id = (chatId ?: payload.url).hashCode()
|
||||
val open = opener(context, instance, id, chatId = chatId)
|
||||
val channel = when (payload.kind) {
|
||||
@@ -176,22 +184,85 @@ object Notifications {
|
||||
NotificationManagerCompat.from(context).notify(notice.id, builder.build())
|
||||
}
|
||||
|
||||
/**
|
||||
* A report was filed (spec 3.8.0): what a scheduled task has to tell, on the Reports channel.
|
||||
* Unlocked: the report's title and its summary. On the lock screen only the public version:
|
||||
* the app's name and "New report" -- nothing from the account (Working-notes rule 5). A tap
|
||||
* and Open go to the report; Mark read marks it, once the phone is unlocked. A run that
|
||||
* filed no report sends nothing, so there is nothing to show for it; a failed run still has
|
||||
* its own notification ([scheduled]).
|
||||
*/
|
||||
private fun report(context: Context, instance: String, payload: PushPayload) {
|
||||
val notice = ReportNotice.from(payload) ?: return
|
||||
NotificationManagerCompat.from(context).notify(notice.id, reportNotification(context, instance, notice))
|
||||
}
|
||||
|
||||
/** The report's notification, apart from posting it, so a test can read both of its faces. */
|
||||
fun reportNotification(context: Context, instance: String, notice: ReportNotice): Notification {
|
||||
val fixed = context.getString(R.string.report_new_public)
|
||||
val open = opener(context, instance, notice.id, chatId = null, reportId = notice.reportId)
|
||||
// A report the model called important goes on a channel of its own that may come up over
|
||||
// what is on screen: on Android 8 and later the channel decides that, not the notification.
|
||||
val channel = if (notice.high) LembasApp.CHANNEL_REPORTS_HIGH else LembasApp.CHANNEL_REPORTS
|
||||
val public = NotificationCompat.Builder(context, channel)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.app_name))
|
||||
.setContentText(fixed)
|
||||
.build()
|
||||
val read = PendingIntent.getBroadcast(
|
||||
context,
|
||||
("read" + notice.reportId).hashCode(),
|
||||
Intent(context, ReportActionReceiver::class.java)
|
||||
.putExtra("instance", instance)
|
||||
.putExtra("report", notice.reportId)
|
||||
.putExtra("notification", notice.id),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
return NotificationCompat.Builder(context, channel)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(notice.title.ifBlank { fixed })
|
||||
.setContentText(notice.summary)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(notice.summary))
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(open)
|
||||
.setCategory(Notification.CATEGORY_STATUS)
|
||||
.setPriority(if (notice.high) NotificationCompat.PRIORITY_HIGH else NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
|
||||
.setPublicVersion(public)
|
||||
.addAction(0, context.getString(R.string.viewer_open), open)
|
||||
.addAction(unlocked(context.getString(R.string.report_mark_read), read))
|
||||
.build()
|
||||
}
|
||||
|
||||
/** The report was read or deleted in the app: its notification has nothing left to say. */
|
||||
fun reportSeen(context: Context, reportId: String) {
|
||||
NotificationManagerCompat.from(context).cancel(ReportNotice.notificationId(reportId))
|
||||
}
|
||||
|
||||
/** A notification action Android runs only once the phone is unlocked. */
|
||||
private fun unlocked(title: String, intent: PendingIntent): NotificationCompat.Action =
|
||||
NotificationCompat.Action.Builder(0, title, intent).setAuthenticationRequired(true).build()
|
||||
|
||||
private fun opener(context: Context, instance: String, id: Int, chatId: String?, scheduleId: String? = null, runId: String? = null): PendingIntent =
|
||||
PendingIntent.getActivity(
|
||||
context,
|
||||
id,
|
||||
Intent(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(EXTRA_CHAT, chatId)
|
||||
.putExtra(EXTRA_SCHEDULE, scheduleId)
|
||||
.putExtra(EXTRA_RUN, runId)
|
||||
.putExtra(EXTRA_INSTANCE, instance),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
private fun opener(
|
||||
context: Context,
|
||||
instance: String,
|
||||
id: Int,
|
||||
chatId: String?,
|
||||
scheduleId: String? = null,
|
||||
runId: String? = null,
|
||||
reportId: String? = null,
|
||||
): PendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
id,
|
||||
Intent(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(EXTRA_CHAT, chatId)
|
||||
.putExtra(EXTRA_SCHEDULE, scheduleId)
|
||||
.putExtra(EXTRA_RUN, runId)
|
||||
.putExtra(EXTRA_REPORT, reportId)
|
||||
.putExtra(EXTRA_INSTANCE, instance),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
private fun scheduleAction(context: Context, instance: String, schedule: String, notification: Int, action: String): PendingIntent =
|
||||
PendingIntent.getBroadcast(
|
||||
@@ -242,6 +313,24 @@ class CardActionReceiver : BroadcastReceiver() {
|
||||
}
|
||||
}
|
||||
|
||||
/** A report's Mark read, from its notification. */
|
||||
class ReportActionReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val pending = goAsync()
|
||||
val instance = intent.getStringExtra("instance") ?: return pending.finish()
|
||||
val report = intent.getStringExtra("report") ?: return pending.finish()
|
||||
background.launch {
|
||||
try {
|
||||
// A report that is gone is as good as read; the notification goes either way.
|
||||
Push.instance(context, instance)?.let { found -> runCatching { context.lembas.instances.clientFor(found).readReport(report) } }
|
||||
NotificationManagerCompat.from(context).cancel(intent.getIntExtra("notification", 0))
|
||||
} finally {
|
||||
pending.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A scheduled task's Pause or Run again, from its notification. */
|
||||
class ScheduleActionReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package eu.llembas.android.push
|
||||
|
||||
import eu.llembas.android.api.PushPayload
|
||||
import eu.llembas.android.api.safeId
|
||||
|
||||
/**
|
||||
* What a filed report's push asks the app to show (harness spec 3.8.0, `reports.md` §4:
|
||||
* notifications come from the report, not from the run). [title] and [summary] are a model's
|
||||
* words about the person's own things: for an unlocked phone only. The lock screen gets the
|
||||
* app's fixed words and nothing else. A payload without the id falls back to its `url`
|
||||
* (`/reports/{id}`), as a browser would open it.
|
||||
*/
|
||||
data class ReportNotice(val reportId: String, val title: String, val summary: String, val high: Boolean) {
|
||||
/** One notification per report: a later push about the same report replaces it. */
|
||||
val id: Int get() = notificationId(reportId)
|
||||
|
||||
companion object {
|
||||
const val KIND = "report"
|
||||
|
||||
/** The notification of the report with this id: what is cancelled once the report is read or deleted in the app. */
|
||||
fun notificationId(reportId: String): Int = "report:$reportId".hashCode()
|
||||
|
||||
fun from(payload: PushPayload): ReportNotice? {
|
||||
if (payload.kind != KIND) return null
|
||||
// Only an id that looks like one: it becomes part of a route and of an address.
|
||||
val id = safeId(payload.reportId?.takeIf { it.isNotBlank() } ?: fromUrl(payload.url)) ?: return null
|
||||
// The report's own words are in the payload's `notification` (the payload's top is
|
||||
// what an older client would show: the app's name and "New report"). A payload
|
||||
// without one is read by its top.
|
||||
val words = payload.notification
|
||||
return ReportNotice(
|
||||
reportId = id,
|
||||
title = words?.title ?: payload.title,
|
||||
summary = words?.body ?: payload.body,
|
||||
high = (words?.importance?.ifBlank { null } ?: payload.importance) == "high",
|
||||
)
|
||||
}
|
||||
|
||||
/** `/reports/{id}` → the id; null for anything else. */
|
||||
fun fromUrl(url: String): String? {
|
||||
if (!url.startsWith("/reports/")) return null
|
||||
return url.removePrefix("/reports/").substringBefore('?').substringBefore('/').takeIf { it.isNotBlank() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package eu.llembas.android.push
|
||||
|
||||
import eu.llembas.android.api.PushPayload
|
||||
import eu.llembas.android.api.safeId
|
||||
|
||||
/**
|
||||
* What a scheduled run's push asks the app to show, read from the server's payload alone
|
||||
@@ -40,8 +41,9 @@ data class ScheduledNotice(
|
||||
fun from(payload: PushPayload): ScheduledNotice? {
|
||||
if (payload.kind != KIND_RESULT && payload.kind != KIND_FAILED) return null
|
||||
val (urlSchedule, urlRun) = fromUrl(payload.url)
|
||||
val schedule = payload.scheduleId?.takeIf { it.isNotBlank() } ?: urlSchedule ?: return null
|
||||
val run = payload.runId?.takeIf { it.isNotBlank() } ?: urlRun
|
||||
// Only ids that look like ids: they become parts of a route and of an address.
|
||||
val schedule = safeId(payload.scheduleId?.takeIf { it.isNotBlank() } ?: urlSchedule) ?: return null
|
||||
val run = safeId(payload.runId?.takeIf { it.isNotBlank() } ?: urlRun)
|
||||
val failed = payload.kind == KIND_FAILED
|
||||
val words = payload.notification
|
||||
val ask = words?.ask?.takeIf { it.isNotBlank() } ?: payload.ask
|
||||
|
||||
@@ -4,111 +4,254 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.provider.OpenableColumns
|
||||
import android.widget.Toast
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.IntentCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.assist.AssistSheetFrame
|
||||
import eu.llembas.android.assist.LastAssist
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.sendFrom
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.files.FolderPicker
|
||||
import eu.llembas.android.ui.files.LocalFile
|
||||
import eu.llembas.android.ui.files.describe
|
||||
import eu.llembas.android.ui.files.filesSay
|
||||
import eu.llembas.android.ui.files.uploadFrom
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* "Share to LLeMbas": text, a link, a picture or a file from any app starts a new chat with it.
|
||||
* Files are uploaded first and bound to the first message, as the composer's are.
|
||||
* "Ask LLeMbas" in any app's share menu: text, a link, a picture or files. A sheet over the app
|
||||
* it came from says what came in, takes a line of what to do with it, and sends it to a new chat
|
||||
* or to the last chat the assistant made; files are uploaded first and bound to that message, as
|
||||
* the composer's are. The chat then opens in the app. A new chat made here becomes the
|
||||
* assistant's last chat, so the next share can follow it.
|
||||
*
|
||||
* The instance is asked nothing until the person has chosen what to do, and no request starts
|
||||
* while the phone is locked or the sheet is not in front ([eu.llembas.android.InstanceGate]).
|
||||
*/
|
||||
class ShareActivity : ComponentActivity() {
|
||||
private val failure = mutableStateOf<String?>(null)
|
||||
class ShareActivity :
|
||||
ComponentActivity(),
|
||||
ShareActions {
|
||||
private val state = MutableStateFlow(ShareState())
|
||||
|
||||
/** The files that came in and may be sent on ([SharedSource]), as the provider describes each. */
|
||||
private var files: List<LocalFile> = emptyList()
|
||||
private val choosing = MutableStateFlow(false)
|
||||
|
||||
/** How far "Save to Files" got into which folder: a second try takes it up at the one that failed. */
|
||||
private var kept = Kept()
|
||||
|
||||
/** The attachments already uploaded for which chat (null: a new one), so a second try does not upload them again. */
|
||||
private var attached: Pair<String?, List<String>> = null to emptyList()
|
||||
private var homeAsked = false
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
val given = when (intent.action) {
|
||||
Intent.ACTION_SEND -> listOfNotNull(IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java))
|
||||
Intent.ACTION_SEND_MULTIPLE -> IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java).orEmpty()
|
||||
else -> emptyList()
|
||||
}
|
||||
// The addresses are the other app's word: one that names something of this app's own is never opened.
|
||||
val taken = given.filter { SharedSource.acceptable(this, it) }
|
||||
val text = listOfNotNull(intent.getStringExtra(Intent.EXTRA_SUBJECT), intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString())
|
||||
.filter { it.isNotBlank() }
|
||||
.distinct()
|
||||
.joinToString("\n\n")
|
||||
.trim()
|
||||
state.update { it.copy(text = text, refused = taken.size < given.size, reading = taken.isNotEmpty()) }
|
||||
lifecycleScope.launch {
|
||||
// What each is called and how large, from its provider, before anything can be sent. The instance is asked nothing yet.
|
||||
files = withContext(Dispatchers.IO) { taken.map { contentResolver.describe(it) } }
|
||||
state.update { it.copy(files = files.map { f -> SharedFile(f.name, f.mime.startsWith("image/"), f.size) }, reading = false) }
|
||||
}
|
||||
lifecycleScope.launch {
|
||||
val store = lembas.instances
|
||||
val prefs = store.prefs.first()
|
||||
state.update {
|
||||
it.copy(
|
||||
signedIn = store.current() != null,
|
||||
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
|
||||
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
|
||||
)
|
||||
}
|
||||
}
|
||||
setContent {
|
||||
LembasTheme {
|
||||
Surface(Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
val error = failure.value
|
||||
if (error == null) {
|
||||
CircularProgressIndicator()
|
||||
Text(stringResource(R.string.share_sending))
|
||||
} else {
|
||||
Text(error, color = MaterialTheme.colorScheme.error)
|
||||
TextButton(onClick = { finish() }) { Text(stringResource(R.string.close)) }
|
||||
}
|
||||
}
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
val shown by state.collectAsState()
|
||||
val picking by choosing.collectAsState()
|
||||
LembasTheme(prefs.theme) {
|
||||
AssistSheetFrame(onDismiss = ::cancel) { handle, _ -> ShareSheetContent(shown, this@ShareActivity, handle) }
|
||||
if (picking) {
|
||||
FolderPicker(
|
||||
stringResource(R.string.files_choose_folder),
|
||||
stringResource(R.string.files_save_here),
|
||||
shown.folder ?: "/",
|
||||
onPick = { folder ->
|
||||
choosing.value = false
|
||||
state.update { it.copy(folder = folder) }
|
||||
},
|
||||
onDismiss = { choosing.value = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
lifecycleScope.launch { share(intent) }
|
||||
}
|
||||
|
||||
private suspend fun share(intent: Intent) {
|
||||
try {
|
||||
val api = lembas.instances.client() ?: run {
|
||||
startActivity(Intent(this, MainActivity::class.java))
|
||||
finish()
|
||||
return
|
||||
}
|
||||
val text = listOfNotNull(
|
||||
intent.getStringExtra(Intent.EXTRA_SUBJECT),
|
||||
intent.getStringExtra(Intent.EXTRA_TEXT),
|
||||
).joinToString("\n\n").trim()
|
||||
val uris = when (intent.action) {
|
||||
Intent.ACTION_SEND -> listOfNotNull(IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java))
|
||||
override fun cancel() = finish()
|
||||
|
||||
Intent.ACTION_SEND_MULTIPLE ->
|
||||
IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java).orEmpty()
|
||||
override fun chooseFolder() {
|
||||
choosing.value = true
|
||||
}
|
||||
|
||||
else -> emptyList()
|
||||
/** The gate, before a request: nothing is sent while the phone is locked or the sheet is not in front. */
|
||||
private suspend fun turn() = lembas.gate.pass { waiting -> state.update { it.copy(waiting = waiting) } }
|
||||
|
||||
/**
|
||||
* "Save to Files" was chosen: only now is the instance asked where the person's files
|
||||
* open, once. Until it answers there is no folder and nothing can be saved; the folder
|
||||
* picker works either way.
|
||||
*/
|
||||
override fun toFiles() {
|
||||
if (homeAsked || state.value.folder != null) return
|
||||
homeAsked = true
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
turn()
|
||||
val home = lembas.instances.client()?.files("/")?.path ?: return@launch
|
||||
state.update { it.copy(folder = it.folder ?: home) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
homeAsked = false
|
||||
state.update { it.copy(error = filesSay(e)) }
|
||||
}
|
||||
val files = uris.map { uri ->
|
||||
val (name, bytes) = withContext(Dispatchers.IO) {
|
||||
val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
|
||||
if (c.moveToFirst()) c.getString(0) else null
|
||||
} ?: "shared"
|
||||
name to (contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep what was shared in the person's files: each file streamed into the folder as it is,
|
||||
* the text (when there is any) as a note beside them. No chat is made and no model is asked.
|
||||
* What the instance refuses -- a file over its limit, a folder that may not be written --
|
||||
* is said in its own sentence, and the sheet stays; Save again goes on from the file that
|
||||
* failed, into the same folder, and does not send the ones before it twice.
|
||||
*/
|
||||
override fun saveToFiles() {
|
||||
val now = state.value
|
||||
val folder = now.folder ?: return
|
||||
if (now.sending) return
|
||||
state.update { it.copy(sending = true, error = null) }
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
val api = lembas.instances.client() ?: run {
|
||||
startActivity(Intent(this@ShareActivity, MainActivity::class.java))
|
||||
finish()
|
||||
return@launch
|
||||
}
|
||||
api.upload(name, contentResolver.getType(uri) ?: "application/octet-stream", bytes).id
|
||||
}
|
||||
if (text.isBlank() && files.isEmpty()) {
|
||||
// The files, then the text as a note (null): one queue, so a second try knows where it was.
|
||||
val items: List<LocalFile?> = if (now.text.isNotBlank()) files + listOf<LocalFile?>(null) else files
|
||||
kept = kept.into(folder)
|
||||
sendFrom(items, kept.done, { turn() }, { kept = kept.copy(done = it) }) { file ->
|
||||
if (file != null) {
|
||||
api.uploadFrom(this@ShareActivity, file, folder)
|
||||
} else {
|
||||
// The note is new each time: never over one that is there.
|
||||
api.saveFile(FileKinds.child(folder, sharedNoteName(java.time.LocalDateTime.now())), now.text + "\n", create = true)
|
||||
}
|
||||
}
|
||||
Toast.makeText(this@ShareActivity, R.string.files_uploaded, Toast.LENGTH_SHORT).show()
|
||||
finish()
|
||||
return
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state.update { it.copy(sending = false, error = filesSay(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun send(ask: String, toLast: Boolean) {
|
||||
if (state.value.sending) return
|
||||
state.update { it.copy(sending = true, error = null) }
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
val store = lembas.instances
|
||||
val api = store.client() ?: run {
|
||||
startActivity(Intent(this@ShareActivity, MainActivity::class.java))
|
||||
finish()
|
||||
return@launch
|
||||
}
|
||||
val now = state.value
|
||||
val into = if (toLast) now.last?.chatId else null
|
||||
// What a first try already uploaded for this chat is not uploaded again.
|
||||
if (attached.first != into) attached = into to emptyList()
|
||||
val ids = attached.second.toMutableList()
|
||||
sendFrom(files, ids.size, { turn() }, { attached = into to ids.toList() }) { file ->
|
||||
val bytes = withContext(Dispatchers.IO) { SharedSource.open(this@ShareActivity, file.uri).use { it.readBytes() } }
|
||||
ids += api.upload(file.name, file.mime, bytes, into).id
|
||||
}
|
||||
val sent = ids.toList()
|
||||
val message = shareMessage(ask, now.text, getString(R.string.share_default_prompt))
|
||||
turn()
|
||||
val chatId = if (into != null) {
|
||||
api.sendMessage(into, message, sent)
|
||||
into
|
||||
} else {
|
||||
val prefs = store.prefs.first()
|
||||
// The assistant's model while the instance still has it; a model that is
|
||||
// gone is not asked for (the instance's default answers instead).
|
||||
val chosen = prefs.assistantModel
|
||||
val gone = chosen.isNotBlank() && runCatching { api.models() }.getOrNull()?.let { it.named(chosen) == null } == true
|
||||
turn()
|
||||
val made = api.createChat(message, sent, model = chosen.takeIf { it.isNotBlank() && !gone })
|
||||
store.savePrefs {
|
||||
it.copy(
|
||||
lastAssistChat = made.chat.id,
|
||||
lastAssistTitle = ask.ifBlank { now.text.ifBlank { now.files.firstOrNull()?.name.orEmpty() } }.take(120),
|
||||
lastAssistAt = System.currentTimeMillis(),
|
||||
)
|
||||
}
|
||||
made.chat.id
|
||||
}
|
||||
startActivity(
|
||||
Intent(this@ShareActivity, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(Notifications.EXTRA_CHAT, chatId),
|
||||
)
|
||||
finish()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// The last chat deleted since: it is not offered again.
|
||||
if (e is ApiException && e.status == 404 && toLast) {
|
||||
lembas.instances.savePrefs { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) }
|
||||
state.update { it.copy(last = null) }
|
||||
}
|
||||
state.update { it.copy(sending = false, error = if (e is SharedRefused) filesSay(e) else explain(e)) }
|
||||
}
|
||||
val made = api.createChat(text.ifBlank { getString(R.string.share_default_prompt) }, files)
|
||||
startActivity(
|
||||
Intent(this, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(Notifications.EXTRA_CHAT, made.chat.id),
|
||||
)
|
||||
finish()
|
||||
} catch (e: Exception) {
|
||||
failure.value = explain(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
package eu.llembas.android.share
|
||||
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.History
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TextFieldDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.assist.LastAssist
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
/** One shared file, as the sheet names it: what its provider calls it and how large it says it is ([size] -1: it does not say). */
|
||||
data class SharedFile(val name: String, val image: Boolean, val size: Long = -1)
|
||||
|
||||
/** How far a "Save to Files" got: [done] of its queue are in [folder]. Another folder starts at the first again. */
|
||||
data class Kept(val folder: String = "", val done: Int = 0) {
|
||||
fun into(folder: String): Kept = if (folder == this.folder) this else Kept(folder, 0)
|
||||
}
|
||||
|
||||
/** A shared address that is not taken: not `content:`, this app's own provider, or one that opens onto this app's own files. */
|
||||
class SharedRefused : java.io.IOException("")
|
||||
|
||||
/** What was shared, where it may go, and how sending it went. */
|
||||
data class ShareState(
|
||||
val signedIn: Boolean = true,
|
||||
val text: String = "",
|
||||
val files: List<SharedFile> = emptyList(),
|
||||
/** The last chat the assistant made, offered as the other place to send it. */
|
||||
val last: LastAssist? = null,
|
||||
val sending: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** Where "Save to Files" would put it: the person's own folder until they choose another; null while it is not known. */
|
||||
val folder: String? = null,
|
||||
/** Something that came in was left out: its address named what another app may not have sent on ([SharedSource]). */
|
||||
val refused: Boolean = false,
|
||||
/** The files are still being asked what they are called. */
|
||||
val reading: Boolean = false,
|
||||
/** The next request waits for the phone to be unlocked and the sheet to be in front. */
|
||||
val waiting: Boolean = false,
|
||||
)
|
||||
|
||||
/** What the share sheet can do; nothing by default, for the screenshot tests. */
|
||||
interface ShareActions {
|
||||
/** Send it with [ask] (empty: the default request) to a new chat, or [toLast] to the last assistant chat. */
|
||||
fun send(ask: String, toLast: Boolean) {}
|
||||
|
||||
/** Keep what was shared as files in [ShareState.folder], asking no model anything. */
|
||||
fun saveToFiles() {}
|
||||
|
||||
/** "Save to Files" was chosen as where it goes: the instance may now be asked where the person's files open. */
|
||||
fun toFiles() {}
|
||||
|
||||
/** Choose another folder to save into. */
|
||||
fun chooseFolder() {}
|
||||
|
||||
fun cancel() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The share sheet's contents, from [state] alone: what came in (the text, the files by name),
|
||||
* what to do with it (a line of the person's own, optional), where it goes -- a new chat, the
|
||||
* last chat the assistant made, or the person's Files, where nothing is asked of a model -- and
|
||||
* Send or Save. Rows of unknown height stack; the choices are whole-row tap targets of at least
|
||||
* 56 dp.
|
||||
*/
|
||||
@Composable
|
||||
fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, handle: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
var ask by remember { mutableStateOf("") }
|
||||
var toLast by remember { mutableStateOf(false) }
|
||||
var toFiles by remember { mutableStateOf(false) }
|
||||
val last = state.last
|
||||
|
||||
Column(handle.fillMaxWidth()) {
|
||||
Box(Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 6.dp), contentAlignment = Alignment.Center) {
|
||||
Box(Modifier.size(width = 36.dp, height = 4.dp).background(palette.inkFaint, RoundedCornerShape(2.dp)))
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.share_label),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp),
|
||||
)
|
||||
if (state.sending) {
|
||||
val bar = Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(2.dp)
|
||||
if (LocalInspectionMode.current) LinearProgressIndicator(progress = { 0.4f }, modifier = bar) else LinearProgressIndicator(bar)
|
||||
}
|
||||
}
|
||||
|
||||
if (!state.signedIn) {
|
||||
Column(Modifier.weight(1f).fillMaxWidth().padding(24.dp), verticalArrangement = Arrangement.Center) {
|
||||
Text(stringResource(R.string.assist_signed_out), style = MaterialTheme.typography.bodyLarge)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
// What came in.
|
||||
if (state.text.isNotBlank()) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(
|
||||
state.text,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 6,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
state.files.forEach { file ->
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 40.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
if (file.image) Icons.Filled.Image else Icons.AutoMirrored.Filled.InsertDriveFile,
|
||||
contentDescription = null,
|
||||
tint = palette.accent,
|
||||
modifier = Modifier.size(24.dp),
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(file.name, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
if (file.size >= 0) {
|
||||
// The name gives; the size is short and stays whole.
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(
|
||||
Formatter.formatShortFileSize(LocalContext.current, file.size),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.refused) Text(stringResource(R.string.share_refused), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
|
||||
// What to do with it.
|
||||
TextField(
|
||||
value = ask,
|
||||
onValueChange = { ask = it },
|
||||
placeholder = { Text(stringResource(R.string.share_ask_hint)) },
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
colors = TextFieldDefaults.colors(
|
||||
focusedContainerColor = palette.surfaceRaised,
|
||||
unfocusedContainerColor = palette.surfaceRaised,
|
||||
focusedIndicatorColor = Color.Transparent,
|
||||
unfocusedIndicatorColor = Color.Transparent,
|
||||
),
|
||||
maxLines = 4,
|
||||
// Files keep what was shared as it is: there is nobody to tell what to do with it.
|
||||
enabled = !state.sending && !toFiles,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
|
||||
)
|
||||
|
||||
// Where it goes.
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column {
|
||||
Destination(Icons.Filled.EditNote, stringResource(R.string.new_chat), null, selected = !toLast && !toFiles, enabled = !state.sending) {
|
||||
toLast = false
|
||||
toFiles = false
|
||||
}
|
||||
if (last != null) {
|
||||
Destination(
|
||||
Icons.Filled.History,
|
||||
stringResource(R.string.assist_continue),
|
||||
last.title,
|
||||
selected = toLast && !toFiles,
|
||||
enabled = !state.sending,
|
||||
) {
|
||||
toLast = true
|
||||
toFiles = false
|
||||
}
|
||||
}
|
||||
Destination(Icons.Filled.Folder, stringResource(R.string.share_to_files), state.folder, selected = toFiles, enabled = !state.sending) {
|
||||
toFiles = true
|
||||
actions.toFiles()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (toFiles) {
|
||||
TextButton(onClick = actions::chooseFolder, enabled = !state.sending, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.files_choose_folder))
|
||||
}
|
||||
}
|
||||
if (state.waiting) Text(stringResource(R.string.files_waiting), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
|
||||
}
|
||||
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(start = 12.dp, end = 16.dp, top = 4.dp, bottom = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.End,
|
||||
) {
|
||||
TextButton(onClick = actions::cancel, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Button(
|
||||
onClick = { if (toFiles) actions.saveToFiles() else actions.send(ask, toLast && last != null) },
|
||||
enabled = !state.sending && !state.reading && (state.text.isNotBlank() || state.files.isNotEmpty()) && (!toFiles || state.folder != null),
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(
|
||||
when {
|
||||
toFiles -> R.string.save
|
||||
state.sending -> R.string.share_sending
|
||||
else -> R.string.send
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Destination(icon: ImageVector, title: String, detail: String?, selected: Boolean, enabled: Boolean, onClick: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.selectable(selected = selected, enabled = enabled, role = Role.RadioButton, onClick = onClick)
|
||||
.heightIn(min = 56.dp)
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(24.dp))
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge)
|
||||
detail?.takeIf { it.isNotBlank() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
RadioButton(selected = selected, onClick = null, enabled = enabled)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The message a share sends: the person's own words (or the default request) first, then what was
|
||||
* shared, so the model reads the request before the material.
|
||||
*/
|
||||
fun shareMessage(ask: String, shared: String, fallback: String): String {
|
||||
val request = ask.trim().ifBlank { fallback }
|
||||
return if (shared.isBlank()) request else "$request\n\n---\n\n${shared.trim()}"
|
||||
}
|
||||
|
||||
/** What shared text is called when it is kept as a file: `shared-20260102-030405.txt`, from the moment it was saved. */
|
||||
fun sharedNoteName(at: java.time.LocalDateTime): String =
|
||||
"shared-" + at.format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss", java.util.Locale.ROOT)) + ".txt"
|
||||
@@ -0,0 +1,77 @@
|
||||
package eu.llembas.android.share
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.system.Os
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
|
||||
/**
|
||||
* What another app may hand this one to send on. A share names its files by address, and the
|
||||
* address is the other app's word: it could as well name something of this app's own -- a file
|
||||
* in its private data, a copy in its cache through its own provider -- and have the person send
|
||||
* it to a chat without knowing. So only a `content:` address of another app's provider is taken,
|
||||
* and what it opens must not be a file of this app's.
|
||||
*/
|
||||
object SharedSource {
|
||||
/**
|
||||
* Whether an address is refused by its looks: anything that is not `content:` (a `file:`
|
||||
* path is read with this app's own rights), and a provider that is this app's ([own]: its
|
||||
* authorities). An authority may carry a user before an `@`; the provider is what follows.
|
||||
*/
|
||||
fun refused(scheme: String?, authority: String?, own: Set<String>): Boolean {
|
||||
if (!scheme.equals("content", ignoreCase = true)) return true
|
||||
val provider = authority?.substringAfterLast('@')?.lowercase().orEmpty()
|
||||
return provider.isBlank() || provider in own.map { it.lowercase() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [resolved] -- where an opened descriptor really leads -- is inside one of [roots],
|
||||
* this app's private places. Compared by whole path segments: `/data/user/0/app` does not
|
||||
* hold `/data/user/0/app.other`.
|
||||
*/
|
||||
fun inside(resolved: String, roots: List<String>): Boolean = roots.any { root ->
|
||||
val base = root.trimEnd('/')
|
||||
base.isNotEmpty() && (resolved == base || resolved.startsWith("$base/"))
|
||||
}
|
||||
|
||||
/** This app's providers, by authority: its own FileProvider and whatever its libraries declare. */
|
||||
fun ownAuthorities(context: Context): Set<String> {
|
||||
val declared = runCatching {
|
||||
@Suppress("DEPRECATION")
|
||||
context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_PROVIDERS).providers
|
||||
}.getOrNull().orEmpty()
|
||||
return declared.flatMap { it.authority.orEmpty().split(';') }.filter { it.isNotBlank() }.toSet() + (context.packageName + ".files")
|
||||
}
|
||||
|
||||
/** This app's private places, as the paths a descriptor can lead to (the data directory under each of its names). */
|
||||
fun privateRoots(context: Context): List<String> {
|
||||
val dirs = listOfNotNull(context.dataDir, context.filesDir?.parentFile, context.cacheDir, context.codeCacheDir, context.noBackupFilesDir) +
|
||||
context.externalCacheDirs.orEmpty().filterNotNull().mapNotNull { it.parentFile } +
|
||||
context.getExternalFilesDirs(null).orEmpty().filterNotNull().mapNotNull { it.parentFile }
|
||||
return dirs.flatMap { listOf(it.absolutePath, runCatching { it.canonicalPath }.getOrDefault(it.absolutePath)) }.distinct()
|
||||
}
|
||||
|
||||
fun acceptable(context: Context, uri: Uri): Boolean = !refused(uri.scheme, uri.authority, ownAuthorities(context))
|
||||
|
||||
/**
|
||||
* Opens what [uri] names for reading, or throws: an address refused by its looks is never
|
||||
* opened, and one that opens onto a file of this app's is closed again unread. The stream
|
||||
* is of the very descriptor that was looked at, so nothing can be swapped in between.
|
||||
*/
|
||||
fun open(context: Context, uri: Uri): InputStream {
|
||||
if (!acceptable(context, uri)) throw SharedRefused()
|
||||
val opened = context.contentResolver.openAssetFileDescriptor(uri, "r") ?: throw IOException("The file could not be opened.")
|
||||
try {
|
||||
val leads = runCatching { Os.readlink("/proc/self/fd/" + opened.parcelFileDescriptor.fd) }.getOrDefault("")
|
||||
val resolved = if (leads.startsWith("/")) runCatching { File(leads).canonicalPath }.getOrDefault(leads) else leads
|
||||
if (inside(resolved, privateRoots(context)) || inside(leads, privateRoots(context))) throw SharedRefused()
|
||||
return opened.createInputStream()
|
||||
} catch (e: Throwable) {
|
||||
runCatching { opened.close() }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.ArrowUpward
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.FolderOff
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.DeviceDirectory
|
||||
import eu.llembas.android.api.DirectoryEntry
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Choosing a folder on a linked computer: the last listing the device gave ([listing]; null
|
||||
* before the first, or where there never was one), the path in the field ([typed]: where the
|
||||
* walk is, or what the person wrote -- the way in that always works), and the sentence for a
|
||||
* listing that could not be had, or that came with one ([error]). [edited]: the person wrote in
|
||||
* the field since the device was last asked, so its answer does not write over them.
|
||||
* [failed]: the last question got no listing.
|
||||
*/
|
||||
data class PickerState(
|
||||
val listing: DeviceDirectory? = null,
|
||||
val loading: Boolean = false,
|
||||
val typed: String = "",
|
||||
val error: String? = null,
|
||||
val edited: Boolean = false,
|
||||
val failed: Boolean = false,
|
||||
)
|
||||
|
||||
/** The most subdirectories shown; a device that names more is cut there. */
|
||||
const val PICKER_ENTRIES = 500
|
||||
|
||||
/** The longest a device's own words are kept: a name, a reason, a sentence. */
|
||||
const val PICKER_WORDS = 300
|
||||
|
||||
private fun String.kept(): String = if (length > PICKER_WORDS) take(PICKER_WORDS) + "…" else this
|
||||
|
||||
/**
|
||||
* A listing as the picker holds it: each path once (the rows are keyed by it), at most
|
||||
* [PICKER_ENTRIES] of them, and the device's words -- names, reasons, a model's name -- cut to
|
||||
* a length that cannot push the controls away.
|
||||
*/
|
||||
fun DeviceDirectory.bounded(): DeviceDirectory = copy(
|
||||
reason = reason.kept(),
|
||||
error = error.kept(),
|
||||
model = model?.let { it.copy(name = it.name.kept(), id = it.id.kept()) },
|
||||
entries = entries.filter { it.path.isNotEmpty() }.distinctBy { it.path }.take(PICKER_ENTRIES).map { entry ->
|
||||
entry.copy(name = entry.name.kept(), reason = entry.reason.kept(), model = entry.model?.let { it.copy(name = it.name.kept(), id = it.id.kept()) })
|
||||
},
|
||||
)
|
||||
|
||||
/** The device is being asked: what is typed from now on is the person's, newer than the answer. */
|
||||
fun PickerState.asking(): PickerState = copy(loading = true, error = null, edited = false)
|
||||
|
||||
/**
|
||||
* The device's answer. A listing is shown ([bounded]) and the field follows it -- unless the
|
||||
* person wrote in the field while the device was answering, or the listing is the places,
|
||||
* which have no path: then the field keeps what it has. A listing may come with a sentence
|
||||
* (part of it could not be read): it is shown with it. No listing -- the device is away, too
|
||||
* old, silent or said no -- leaves the last listing and the typed path where they were, with
|
||||
* the server's sentence ([fallback] where it sent none).
|
||||
*/
|
||||
fun PickerState.took(answer: DeviceDirectory, fallback: String = ""): PickerState = when {
|
||||
answer.listed -> copy(
|
||||
listing = answer.bounded(),
|
||||
loading = false,
|
||||
failed = false,
|
||||
error = answer.error.kept().ifBlank { null },
|
||||
typed = if (edited) typed else answer.path.ifEmpty { typed },
|
||||
)
|
||||
|
||||
else -> copy(loading = false, failed = true, error = answer.error.kept().ifBlank { fallback })
|
||||
}
|
||||
|
||||
/** The device could not be asked at all ([said]: why): as an answer without a listing. */
|
||||
fun PickerState.unanswered(said: String): PickerState = copy(loading = false, failed = true, error = said.kept())
|
||||
|
||||
/**
|
||||
* Where "up" leads from the listing shown: the parent, the places (`""`) from a directory that
|
||||
* has none, or null at the places themselves and where nothing is listed -- there the picker
|
||||
* closes instead.
|
||||
*/
|
||||
val PickerState.up: String?
|
||||
get() = listing?.takeIf { !it.places }?.parent
|
||||
|
||||
/**
|
||||
* Where Back leads: up a level, or null to close -- at the top, and after a question that got
|
||||
* no listing (the device went away mid-walk), where "up" would only ask it again for ever.
|
||||
*/
|
||||
val PickerState.back: String?
|
||||
get() = if (failed) null else up
|
||||
|
||||
/**
|
||||
* Whether the path in the field may be chosen: something is written, and it is not the listed
|
||||
* directory the device said it would open no session in. A path the device was never asked
|
||||
* about may be chosen: the instance checks it when it is used.
|
||||
*/
|
||||
val PickerState.canChoose: Boolean
|
||||
get() = typed.isNotBlank() && !refusedHere
|
||||
|
||||
/** The field holds the listed directory, and the device will not open a session there. */
|
||||
val PickerState.refusedHere: Boolean
|
||||
get() = listing?.let { !it.places && !it.accepted && it.path == typed.trim() } == true
|
||||
|
||||
interface PickerActions {
|
||||
fun open(path: String) {}
|
||||
fun typed(text: String) {}
|
||||
fun choose() {}
|
||||
fun back() {}
|
||||
fun close() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The directory picker over whatever asked for it: [load] asks the device for a path (`""`:
|
||||
* its places), [onPick] is given the chosen path. It opens at [initial], or at the places.
|
||||
* Back goes up a level, and closes at the top.
|
||||
*/
|
||||
@Composable
|
||||
fun DirectoryPicker(title: String, initial: String, load: suspend (String) -> DeviceDirectory, onPick: (String) -> Unit, onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember { mutableStateOf(PickerState(typed = initial.trim(), loading = true)) }
|
||||
var reading by remember { mutableStateOf<Job?>(null) }
|
||||
val fallback = stringResource(R.string.directory_no_listing)
|
||||
val read: (String) -> Unit = { path ->
|
||||
reading?.cancel()
|
||||
state = state.asking()
|
||||
reading = scope.launch {
|
||||
try {
|
||||
val answer = load(path)
|
||||
// Applied to the state as it is now: `took` leaves what was typed meanwhile.
|
||||
state = state.took(answer, fallback)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state = state.unanswered(context.explain(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) { read(initial.trim()) }
|
||||
val actions = object : PickerActions {
|
||||
override fun open(path: String) = read(path)
|
||||
|
||||
override fun typed(text: String) {
|
||||
state = state.copy(typed = text, edited = true)
|
||||
}
|
||||
|
||||
override fun choose() {
|
||||
if (state.canChoose) onPick(state.typed.trim())
|
||||
}
|
||||
|
||||
override fun back() {
|
||||
val up = state.back
|
||||
if (up == null) onDismiss() else read(up)
|
||||
}
|
||||
|
||||
override fun close() = onDismiss()
|
||||
}
|
||||
Dialog(onDismissRequest = actions::back, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
DirectoryPickerContent(title, state, actions)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The picker, drawn from its state: where the walk is, the model last used there, the
|
||||
* subdirectories (a row is 56 dp; its name gives, the model beside it keeps to a third), and at
|
||||
* the foot the path as text with Choose -- which is all there is when the device lists nothing.
|
||||
*/
|
||||
@Composable
|
||||
fun DirectoryPickerContent(title: String, state: PickerState, actions: PickerActions, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val listing = state.listing
|
||||
Surface(color = palette.bg, contentColor = palette.ink, modifier = modifier.fillMaxSize()) {
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 56.dp).padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
IconButton(onClick = actions::back) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
Text(title, style = MaterialTheme.typography.titleLarge, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
if (state.loading) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.padding(horizontal = 12.dp).size(20.dp))
|
||||
IconButton(onClick = actions::close) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) }
|
||||
}
|
||||
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(
|
||||
listing?.path?.ifEmpty { null } ?: stringResource(R.string.directory_places),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontFamily = if (listing?.places == false) FontFamily.Monospace else null,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
listing?.model?.let {
|
||||
Text(
|
||||
stringResource(R.string.directory_last_used, it.label),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (listing != null && !listing.places && !listing.accepted) {
|
||||
Text(
|
||||
listing.reason.ifBlank { stringResource(R.string.directory_refused) },
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.warning,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
state.error?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger, maxLines = 4, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxWidth().weight(1f).padding(top = 8.dp)) {
|
||||
// The way out of a directory, and -- where nothing is listed -- the way to the places.
|
||||
if (listing?.places != true) {
|
||||
item(key = "up") {
|
||||
val places = listing == null || listing.parent.isEmpty()
|
||||
EntryRow(
|
||||
name = stringResource(if (places) R.string.directory_all_places else R.string.directory_up),
|
||||
icon = { Icon(Icons.Filled.ArrowUpward, contentDescription = null, tint = palette.inkMuted) },
|
||||
onClick = { actions.open(listing?.parent.orEmpty()) },
|
||||
)
|
||||
}
|
||||
}
|
||||
if (listing != null && listing.entries.isEmpty() && !state.loading) {
|
||||
item(key = "empty") {
|
||||
Text(
|
||||
stringResource(if (listing.places) R.string.directory_no_places else R.string.directory_empty),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
items(listing?.entries.orEmpty(), key = { "d:" + it.path }) { entry -> Entry(entry, onOpen = { actions.open(entry.path) }) }
|
||||
}
|
||||
HorizontalDivider(color = palette.border)
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedTextField(
|
||||
value = state.typed,
|
||||
onValueChange = actions::typed,
|
||||
singleLine = true,
|
||||
label = { Text(stringResource(R.string.directory_path)) },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.End),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TextButton(onClick = actions::close, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) }
|
||||
Button(onClick = actions::choose, enabled = state.canChoose, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.directory_choose))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A subdirectory: its name, why no session opens in it where none does, and the model last used in it. */
|
||||
@Composable
|
||||
private fun Entry(entry: DirectoryEntry, onOpen: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
EntryRow(
|
||||
name = entry.name.ifBlank { entry.path },
|
||||
note = if (entry.accepted) null else entry.reason.ifBlank { stringResource(R.string.directory_not_trusted) },
|
||||
model = entry.model?.label,
|
||||
icon = {
|
||||
Icon(
|
||||
if (entry.accepted) Icons.Filled.Folder else Icons.Filled.FolderOff,
|
||||
contentDescription = null,
|
||||
tint = if (entry.accepted) palette.accent else palette.inkFaint,
|
||||
)
|
||||
},
|
||||
onClick = onOpen,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryRow(name: String, icon: @Composable () -> Unit, onClick: () -> Unit, note: String? = null, model: String? = null) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable(onClick = onClick).heightIn(min = 56.dp).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) { icon() }
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
note?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 2, overflow = TextOverflow.Ellipsis) }
|
||||
}
|
||||
model?.let {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.widthIn(max = 120.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import eu.llembas.android.ui.theme.Palette
|
||||
|
||||
/**
|
||||
* Syntax highlighting for code that is only read: the file viewer and a reply's code blocks.
|
||||
*
|
||||
* A small scanner of the app's own, not a library: what it has to tell apart is few -- comments,
|
||||
* strings, numbers, keywords, type names, and a markup language's tags -- and a highlighter that
|
||||
* is a parser of its own (Prism4j, which needs an annotation processor and has not moved since
|
||||
* 2019; or a WebView, which the app does not have) would be more to trust than the result is worth.
|
||||
* It never runs anything and never fails: a language it does not know, or text it does not
|
||||
* follow, is simply drawn plain. The colours are the theme's tokens, so it follows Shire and
|
||||
* Moria like everything else.
|
||||
*
|
||||
* The languages are the server's (`show`'s `language`, from the file's extension) and a fence's
|
||||
* info string in a reply (```kotlin), with the usual short names.
|
||||
*/
|
||||
enum class TokenKind { Comment, Text, Number, Keyword, Type, Tag, Attribute }
|
||||
|
||||
data class Token(val start: Int, val end: Int, val kind: TokenKind)
|
||||
|
||||
/** How one language is read: the scanner's few settings. */
|
||||
private data class Spec(
|
||||
val keywords: Set<String> = emptySet(),
|
||||
val lineComments: List<String> = emptyList(),
|
||||
val blockComments: List<Pair<String, String>> = emptyList(),
|
||||
/** String delimiters, longest first (""" before "). */
|
||||
val strings: List<String> = listOf("\"", "'"),
|
||||
val ignoreCase: Boolean = false,
|
||||
/** A capitalised identifier is a type (Kotlin, Java, Swift, Rust...). */
|
||||
val capitalisedTypes: Boolean = false,
|
||||
/** `<tag attr="...">`: markup (XML, HTML, Vue and Svelte templates). */
|
||||
val markup: Boolean = false,
|
||||
/** `key:` / `key =` at a line's start is the key (YAML, TOML). */
|
||||
val keys: Boolean = false,
|
||||
/** `$name` / `${...}` variables (shells, PHP). */
|
||||
val dollarVariables: Boolean = false,
|
||||
)
|
||||
|
||||
private fun words(text: String): Set<String> = text.split(' ').filter { it.isNotBlank() }.toSet()
|
||||
|
||||
private val C_FAMILY = words(
|
||||
"if else for while do switch case default break continue return goto sizeof typedef struct union enum " +
|
||||
"static const extern volatile register inline void char short int long float double signed unsigned " +
|
||||
"auto true false NULL nullptr",
|
||||
)
|
||||
private val CPP = C_FAMILY + words(
|
||||
"class namespace template typename public private protected virtual override final new delete this " +
|
||||
"using operator friend explicit constexpr noexcept try catch throw bool std",
|
||||
)
|
||||
private val JAVA = words(
|
||||
"abstract assert boolean break byte case catch char class const continue default do double else enum " +
|
||||
"extends final finally float for goto if implements import instanceof int interface long native new " +
|
||||
"package private protected public return short static strictfp super switch synchronized this throw " +
|
||||
"throws transient try void volatile while true false null var record sealed permits yield",
|
||||
)
|
||||
private val KOTLIN = words(
|
||||
"as break class continue do else false for fun if in interface is null object package return super this " +
|
||||
"throw true try typealias typeof val var when while by catch constructor delegate dynamic field file " +
|
||||
"finally get import init param property receiver set setparam where actual abstract annotation " +
|
||||
"companion const crossinline data enum expect external final infix inline inner internal lateinit " +
|
||||
"noinline open operator out override private protected public reified sealed suspend tailrec vararg value",
|
||||
)
|
||||
private val JS = words(
|
||||
"break case catch class const continue debugger default delete do else export extends finally for " +
|
||||
"function if import in instanceof new return super switch this throw try typeof var void while with " +
|
||||
"yield let static async await of true false null undefined from as get set",
|
||||
)
|
||||
private val TS = JS + words(
|
||||
"interface type enum implements declare namespace module public private protected readonly abstract " +
|
||||
"keyof infer is never unknown any string number boolean symbol bigint object satisfies",
|
||||
)
|
||||
private val PYTHON = words(
|
||||
"False None True and as assert async await break class continue def del elif else except finally for " +
|
||||
"from global if import in is lambda nonlocal not or pass raise return try while with yield match case self",
|
||||
)
|
||||
private val RUST = words(
|
||||
"as async await break const continue crate dyn else enum extern false fn for if impl in let loop match " +
|
||||
"mod move mut pub ref return self Self static struct super trait true type unsafe use where while",
|
||||
)
|
||||
private val GO = words(
|
||||
"break case chan const continue default defer else fallthrough for func go goto if import interface map " +
|
||||
"package range return select struct switch type var true false nil iota",
|
||||
)
|
||||
private val RUBY = words(
|
||||
"BEGIN END alias and begin break case class def defined do else elsif end ensure false for if in module " +
|
||||
"next nil not or redo rescue retry return self super then true undef unless until when while yield require",
|
||||
)
|
||||
private val PHP = words(
|
||||
"abstract and array as break callable case catch class clone const continue declare default do echo else " +
|
||||
"elseif empty enddeclare endfor endforeach endif endswitch endwhile extends final finally fn for foreach " +
|
||||
"function global goto if implements include instanceof insteadof interface isset list match namespace new " +
|
||||
"or print private protected public readonly require return static switch throw trait try unset use var " +
|
||||
"while yield true false null",
|
||||
)
|
||||
private val SWIFT = words(
|
||||
"associatedtype class deinit enum extension fileprivate func import init inout internal let open operator " +
|
||||
"private protocol public rethrows static struct subscript typealias var break case continue default defer " +
|
||||
"do else fallthrough for guard if in repeat return switch where while as catch false is nil super self Self " +
|
||||
"throw throws true try async await some any",
|
||||
)
|
||||
private val CSHARP = words(
|
||||
"abstract as base bool break byte case catch char checked class const continue decimal default delegate do " +
|
||||
"double else enum event explicit extern false finally fixed float for foreach goto if implicit in int " +
|
||||
"interface internal is lock long namespace new null object operator out override params private protected " +
|
||||
"public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true " +
|
||||
"try typeof uint ulong unchecked unsafe ushort using virtual void volatile while var async await record",
|
||||
)
|
||||
private val DART = words(
|
||||
"abstract as assert async await break case catch class const continue covariant default deferred do dynamic " +
|
||||
"else enum export extends extension external factory false final finally for get if implements import in " +
|
||||
"interface is late library mixin new null on operator part required rethrow return set show static super " +
|
||||
"switch sync this throw true try typedef var void while with yield",
|
||||
)
|
||||
private val ZIG = words(
|
||||
"addrspace align allowzero and anyframe anytype asm async await break callconv catch comptime const continue " +
|
||||
"defer else enum errdefer error export extern fn for if inline noalias nosuspend noinline opaque or orelse " +
|
||||
"packed pub resume return linksection struct suspend switch test threadlocal try union unreachable usingnamespace " +
|
||||
"var volatile while true false null undefined",
|
||||
)
|
||||
private val SHELL = words(
|
||||
"if then else elif fi case esac for select while until do done in function return exit local export " +
|
||||
"readonly declare set unset shift source echo cd test true false",
|
||||
)
|
||||
private val SQL = words(
|
||||
"select from where and or not insert into values update set delete create table drop alter add index view " +
|
||||
"join left right inner outer full on as group by order having limit offset union all distinct case when then " +
|
||||
"else end null is in like between exists primary key foreign references default unique check begin commit " +
|
||||
"rollback transaction with returning asc desc count sum avg min max integer text real blob varchar",
|
||||
)
|
||||
private val LUA = words(
|
||||
"and break do else elseif end false for function goto if in local nil not or repeat return then true until while",
|
||||
)
|
||||
private val CSS = words("important inherit initial unset none auto")
|
||||
private val LITERALS = words("true false null yes no on off")
|
||||
private val DOCKER = words(
|
||||
"FROM RUN CMD LABEL EXPOSE ENV ADD COPY ENTRYPOINT VOLUME USER WORKDIR ARG ONBUILD STOPSIGNAL HEALTHCHECK SHELL AS",
|
||||
)
|
||||
|
||||
private val C_LIKE = Spec(lineComments = listOf("//"), blockComments = listOf("/*" to "*/"))
|
||||
|
||||
private val SPECS: Map<String, Spec> = buildMap {
|
||||
val js = C_LIKE.copy(keywords = JS, strings = listOf("\"", "'", "`"))
|
||||
val ts = C_LIKE.copy(keywords = TS, strings = listOf("\"", "'", "`"), capitalisedTypes = true)
|
||||
put("javascript", js)
|
||||
put("jsx", js)
|
||||
put("typescript", ts)
|
||||
put("tsx", ts)
|
||||
put("json", Spec(keywords = LITERALS, strings = listOf("\"")))
|
||||
put("python", Spec(keywords = PYTHON, lineComments = listOf("#"), strings = listOf("\"\"\"", "'''", "\"", "'"), capitalisedTypes = true))
|
||||
put("rust", C_LIKE.copy(keywords = RUST, strings = listOf("\""), capitalisedTypes = true))
|
||||
put("go", C_LIKE.copy(keywords = GO, strings = listOf("\"", "`", "'")))
|
||||
put("ruby", Spec(keywords = RUBY, lineComments = listOf("#"), strings = listOf("\"", "'"), capitalisedTypes = true))
|
||||
put("php", C_LIKE.copy(keywords = PHP, lineComments = listOf("//", "#"), dollarVariables = true, ignoreCase = true))
|
||||
put("java", C_LIKE.copy(keywords = JAVA, strings = listOf("\"\"\"", "\"", "'"), capitalisedTypes = true))
|
||||
put("kotlin", C_LIKE.copy(keywords = KOTLIN, strings = listOf("\"\"\"", "\"", "'"), capitalisedTypes = true))
|
||||
put("swift", C_LIKE.copy(keywords = SWIFT, strings = listOf("\"\"\"", "\""), capitalisedTypes = true))
|
||||
put("c", C_LIKE.copy(keywords = C_FAMILY))
|
||||
put("cpp", C_LIKE.copy(keywords = CPP, capitalisedTypes = true))
|
||||
put("csharp", C_LIKE.copy(keywords = CSHARP, capitalisedTypes = true))
|
||||
put("dart", C_LIKE.copy(keywords = DART, strings = listOf("\"\"\"", "'''", "\"", "'"), capitalisedTypes = true))
|
||||
put("zig", C_LIKE.copy(keywords = ZIG, strings = listOf("\"", "'")))
|
||||
val shell = Spec(keywords = SHELL, lineComments = listOf("#"), dollarVariables = true)
|
||||
put("bash", shell)
|
||||
put("fish", shell)
|
||||
put("css", C_LIKE.copy(keywords = CSS, lineComments = emptyList()))
|
||||
put("scss", C_LIKE.copy(keywords = CSS, dollarVariables = true))
|
||||
put("sql", Spec(keywords = SQL, lineComments = listOf("--"), blockComments = listOf("/*" to "*/"), strings = listOf("'", "\""), ignoreCase = true))
|
||||
put("yaml", Spec(keywords = LITERALS, lineComments = listOf("#"), keys = true))
|
||||
put("toml", Spec(keywords = LITERALS, lineComments = listOf("#"), strings = listOf("\"\"\"", "'''", "\"", "'"), keys = true))
|
||||
// Text between tags is prose: an apostrophe in it is not a string. Attribute values are read by markup().
|
||||
val markup = Spec(blockComments = listOf("<!--" to "-->"), strings = emptyList(), markup = true)
|
||||
put("xml", markup)
|
||||
put("html", markup)
|
||||
put("vue", markup)
|
||||
put("svelte", markup)
|
||||
put("lua", Spec(keywords = LUA, lineComments = listOf("--"), blockComments = listOf("--[[" to "]]"), strings = listOf("\"", "'")))
|
||||
put("dockerfile", Spec(keywords = DOCKER, lineComments = listOf("#")))
|
||||
put("makefile", Spec(lineComments = listOf("#"), dollarVariables = true, keys = true))
|
||||
}
|
||||
|
||||
/** A fence's short names for the server's language names. */
|
||||
private val ALIASES = mapOf(
|
||||
"js" to "javascript", "mjs" to "javascript", "cjs" to "javascript", "ts" to "typescript", "py" to "python",
|
||||
"python3" to "python", "rs" to "rust", "golang" to "go", "rb" to "ruby", "kt" to "kotlin", "kts" to "kotlin",
|
||||
"c++" to "cpp", "cc" to "cpp", "hpp" to "cpp", "h" to "c", "cs" to "csharp", "c#" to "csharp", "sh" to "bash",
|
||||
"shell" to "bash", "zsh" to "bash", "console" to "bash", "yml" to "yaml", "svg" to "xml", "htm" to "html",
|
||||
"docker" to "dockerfile", "make" to "makefile", "jsonc" to "json", "json5" to "json", "postgres" to "sql",
|
||||
"postgresql" to "sql", "sqlite" to "sql", "mysql" to "sql",
|
||||
)
|
||||
|
||||
/** Whether [language] is one this highlighter reads. */
|
||||
fun highlights(language: String): Boolean = specOf(language) != null
|
||||
|
||||
private fun specOf(language: String): Spec? {
|
||||
val name = language.trim().lowercase()
|
||||
return SPECS[name] ?: ALIASES[name]?.let { SPECS[it] }
|
||||
}
|
||||
|
||||
/** Larger than this is drawn plain: a megabyte of spans costs more than it helps. */
|
||||
const val HIGHLIGHT_MAX_CHARS = 400_000
|
||||
|
||||
/** The tokens of [text] read as [language]: empty for a language not known, or a text too large. */
|
||||
fun tokenize(text: String, language: String): List<Token> {
|
||||
val spec = specOf(language) ?: return emptyList()
|
||||
if (text.length > HIGHLIGHT_MAX_CHARS) return emptyList()
|
||||
return Scanner(text, spec).run()
|
||||
}
|
||||
|
||||
private class Scanner(private val s: String, private val spec: Spec) {
|
||||
private val out = mutableListOf<Token>()
|
||||
private var i = 0
|
||||
private var lineStart = true
|
||||
|
||||
fun run(): List<Token> {
|
||||
while (i < s.length) {
|
||||
val c = s[i]
|
||||
if (c == '\n') {
|
||||
lineStart = true
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if (c == ' ' || c == '\t') {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
val atLineStart = lineStart
|
||||
lineStart = false
|
||||
if (block() || line() || (spec.markup && markup()) || string() || (spec.keys && atLineStart && key()) ||
|
||||
(spec.dollarVariables && variable()) || number() || word()
|
||||
) {
|
||||
continue
|
||||
}
|
||||
i++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun add(start: Int, end: Int, kind: TokenKind) {
|
||||
if (end > start) out += Token(start, end, kind)
|
||||
}
|
||||
|
||||
private fun block(): Boolean {
|
||||
for ((open, close) in spec.blockComments) {
|
||||
if (s.startsWith(open, i)) {
|
||||
val end = s.indexOf(close, i + open.length).let { if (it < 0) s.length else it + close.length }
|
||||
add(i, end, TokenKind.Comment)
|
||||
i = end
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun line(): Boolean {
|
||||
for (mark in spec.lineComments) {
|
||||
// `#` in a shell word ("a#b") or `$#` is not a comment; one after a space or at a line's start is.
|
||||
if (s.startsWith(mark, i) && (mark != "#" || i == 0 || s[i - 1].isWhitespace())) {
|
||||
val end = s.indexOf('\n', i).let { if (it < 0) s.length else it }
|
||||
add(i, end, TokenKind.Comment)
|
||||
i = end
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun string(): Boolean {
|
||||
for (quote in spec.strings) {
|
||||
if (!s.startsWith(quote, i)) continue
|
||||
// A single-character quote ends at the line's end if it is not closed: a stray
|
||||
// apostrophe ("don't" in a comment-less shell line) colours one line, not the file.
|
||||
var j = i + quote.length
|
||||
while (j < s.length) {
|
||||
if (s[j] == '\\' && quote.length == 1) {
|
||||
j += 2
|
||||
continue
|
||||
}
|
||||
if (s.startsWith(quote, j)) {
|
||||
j += quote.length
|
||||
break
|
||||
}
|
||||
if (s[j] == '\n' && quote.length == 1 && quote != "`") break
|
||||
j++
|
||||
}
|
||||
val end = j.coerceAtMost(s.length)
|
||||
add(i, end, TokenKind.Text)
|
||||
i = end
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun number(): Boolean {
|
||||
val c = s[i]
|
||||
if (!c.isDigit() && !(c == '.' && i + 1 < s.length && s[i + 1].isDigit())) return false
|
||||
if (i > 0 && (s[i - 1].isLetterOrDigit() || s[i - 1] == '_')) return false
|
||||
var j = i
|
||||
while (j < s.length && (s[j].isLetterOrDigit() || s[j] == '.' || s[j] == '_')) j++
|
||||
add(i, j, TokenKind.Number)
|
||||
i = j
|
||||
return true
|
||||
}
|
||||
|
||||
private fun word(): Boolean {
|
||||
val c = s[i]
|
||||
if (!c.isLetter() && c != '_' && c != '@') return false
|
||||
var j = i + 1
|
||||
while (j < s.length && (s[j].isLetterOrDigit() || s[j] == '_')) j++
|
||||
val word = s.substring(i, j)
|
||||
val bare = word.removePrefix("@")
|
||||
when {
|
||||
word.startsWith("@") && word.length > 1 -> add(i, j, TokenKind.Attribute)
|
||||
|
||||
(if (spec.ignoreCase) bare.lowercase() in spec.keywords || bare in spec.keywords else bare in spec.keywords) ->
|
||||
add(i, j, TokenKind.Keyword)
|
||||
|
||||
spec.capitalisedTypes && bare.first().isUpperCase() && bare.any { it.isLowerCase() } -> add(i, j, TokenKind.Type)
|
||||
}
|
||||
i = j
|
||||
return true
|
||||
}
|
||||
|
||||
private fun variable(): Boolean {
|
||||
if (s[i] != '$' || i + 1 >= s.length) return false
|
||||
var j = i + 1
|
||||
if (s[j] == '{') {
|
||||
j = s.indexOf('}', j).let { if (it < 0) s.length else it + 1 }
|
||||
} else {
|
||||
while (j < s.length && (s[j].isLetterOrDigit() || s[j] == '_')) j++
|
||||
}
|
||||
if (j == i + 1) return false
|
||||
add(i, j, TokenKind.Attribute)
|
||||
i = j
|
||||
return true
|
||||
}
|
||||
|
||||
/** `key:` (YAML) or `key =` (TOML, Make) as a line's first word. */
|
||||
private fun key(): Boolean {
|
||||
var j = i
|
||||
if (s[j] == '-' && j + 1 < s.length && s[j + 1] == ' ') return false
|
||||
while (j < s.length && (s[j].isLetterOrDigit() || s[j] in "_-.[]\"'")) j++
|
||||
if (j == i) return false
|
||||
var k = j
|
||||
while (k < s.length && s[k] == ' ') k++
|
||||
if (k < s.length && (s[k] == ':' || s[k] == '=') && (k + 1 >= s.length || s[k + 1] != '=')) {
|
||||
add(i, j, TokenKind.Type)
|
||||
i = j
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** `<tag attr="value">` and `</tag>`: the tag's name, its attributes' names, the values as strings. */
|
||||
private fun markup(): Boolean {
|
||||
if (s[i] != '<' || i + 1 >= s.length) return false
|
||||
var j = i + 1
|
||||
if (s[j] == '/' || s[j] == '?' || s[j] == '!') j++
|
||||
val nameStart = j
|
||||
while (j < s.length && (s[j].isLetterOrDigit() || s[j] in "-_:.")) j++
|
||||
if (j == nameStart) return false
|
||||
add(nameStart, j, TokenKind.Tag)
|
||||
while (j < s.length && s[j] != '>') {
|
||||
when {
|
||||
s[j] == '"' || s[j] == '\'' -> {
|
||||
val q = s[j]
|
||||
val end = s.indexOf(q, j + 1).let { if (it < 0) s.length else it + 1 }
|
||||
add(j, end, TokenKind.Text)
|
||||
j = end
|
||||
}
|
||||
|
||||
s[j].isLetter() -> {
|
||||
val a = j
|
||||
while (j < s.length && (s[j].isLetterOrDigit() || s[j] in "-_:@.")) j++
|
||||
add(a, j, TokenKind.Attribute)
|
||||
}
|
||||
|
||||
s[j] == '\n' -> {
|
||||
j++
|
||||
}
|
||||
|
||||
else -> j++
|
||||
}
|
||||
}
|
||||
i = (j + 1).coerceAtMost(s.length)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/** The theme's colour for each kind of token. */
|
||||
fun tokenStyle(kind: TokenKind, palette: Palette): SpanStyle = when (kind) {
|
||||
TokenKind.Comment -> SpanStyle(color = palette.inkFaint, fontStyle = FontStyle.Italic)
|
||||
TokenKind.Text -> SpanStyle(color = palette.success)
|
||||
TokenKind.Number -> SpanStyle(color = palette.warning)
|
||||
TokenKind.Keyword -> SpanStyle(color = palette.accent)
|
||||
TokenKind.Type -> SpanStyle(color = palette.leaf)
|
||||
TokenKind.Tag -> SpanStyle(color = palette.accent)
|
||||
TokenKind.Attribute -> SpanStyle(color = palette.warning)
|
||||
}
|
||||
|
||||
/** [text] with its [tokens] in the theme's colours; the rest in [plain]. */
|
||||
fun highlighted(text: String, tokens: List<Token>, palette: Palette, plain: Color = palette.ink): AnnotatedString = buildAnnotatedString {
|
||||
append(text)
|
||||
addStyle(SpanStyle(color = plain), 0, text.length)
|
||||
for (token in tokens) addStyle(tokenStyle(token.kind, palette), token.start, token.end.coerceAtMost(text.length))
|
||||
}
|
||||
|
||||
/** [text] as [language], highlighted -- or plain, when the language is not one it reads. */
|
||||
fun highlight(text: String, language: String, palette: Palette): AnnotatedString = highlighted(text, tokenize(text, language), palette)
|
||||
@@ -8,16 +8,54 @@ package eu.llembas.android.ui
|
||||
*
|
||||
* A fence that is not closed yet runs to the end: while a reply is being written, the code it
|
||||
* is in the middle of is already a code block, not markdown that changes shape when it closes.
|
||||
*
|
||||
* **A page** (harness spec 3.8.0, `pages.md`: a whole HTML document in an `html-view` fence) is
|
||||
* not drawn on a phone and its source is never shown as the answer. Which fence is a page is the
|
||||
* server's to say: a block is one only in a reply written while pages were offered, and the
|
||||
* server then puts the one line `[page: Title]` in its place in the text it gives a client that
|
||||
* draws no pages. That line is what becomes [Segment.Page]. A fence is taken for a page here
|
||||
* only where the caller says pages are being written ([splitFences]' `pages`: the open step of
|
||||
* a reply as it streams, which the server has not turned into text yet); anywhere else an
|
||||
* `html-view` fence is the code block it is.
|
||||
*/
|
||||
sealed interface Segment {
|
||||
data class Prose(val markdown: String) : Segment
|
||||
|
||||
data class Code(val language: String, val code: String, val closed: Boolean = true) : Segment
|
||||
|
||||
data class Page(val title: String, val closed: Boolean = true) : Segment
|
||||
}
|
||||
|
||||
/** `pages.fence`: the fence's word, exact. */
|
||||
private const val PAGE_FENCE = "html-view"
|
||||
|
||||
/** `pages.title_max`. */
|
||||
private const val PAGE_TITLE_MAX = 80
|
||||
|
||||
private val PAGE_OPENING = Regex("^ {0,3}(?:`{3,}|~{3,})$PAGE_FENCE(?:\\s+(.*))?$")
|
||||
|
||||
/** `pages.projection`, on a line of its own. */
|
||||
private val PAGE_LINE = Regex("^\\s*\\[page: (.*)]\\s*$")
|
||||
|
||||
/** A page's title as written: white space collapsed, cut to the spec's length; empty when it has none. */
|
||||
private fun pageTitle(raw: String?): String = raw.orEmpty().trim().replace(Regex("\\s+"), " ").take(PAGE_TITLE_MAX)
|
||||
|
||||
/**
|
||||
* A reply's text with every page replaced by the spec's one line, `[page: Title]`: what Copy,
|
||||
* Share and read-aloud take, so a page's source never leaves as "the answer". [untitled] names
|
||||
* a page without a title.
|
||||
*/
|
||||
fun pageProjection(markdown: String, untitled: String, pages: Boolean = false): String = splitFences(markdown, pages).joinToString("\n\n") { segment ->
|
||||
when (segment) {
|
||||
is Segment.Prose -> segment.markdown
|
||||
is Segment.Code -> "```${segment.language}\n${segment.code}\n```"
|
||||
is Segment.Page -> "[page: ${segment.title.ifBlank { untitled }}]"
|
||||
}
|
||||
}
|
||||
|
||||
private val OPENING = Regex("^ {0,3}(`{3,}|~{3,})\\s*([^`\\s]*).*$")
|
||||
|
||||
fun splitFences(markdown: String): List<Segment> {
|
||||
fun splitFences(markdown: String, pages: Boolean = false): List<Segment> {
|
||||
val out = mutableListOf<Segment>()
|
||||
val prose = StringBuilder()
|
||||
val lines = markdown.split("\n")
|
||||
@@ -32,13 +70,20 @@ fun splitFences(markdown: String): List<Segment> {
|
||||
while (i < lines.size) {
|
||||
val open = OPENING.matchEntire(lines[i])
|
||||
if (open == null) {
|
||||
prose.append(lines[i]).append('\n')
|
||||
val page = PAGE_LINE.matchEntire(lines[i])
|
||||
if (page != null) {
|
||||
flushProse()
|
||||
out += Segment.Page(pageTitle(page.groupValues[1]))
|
||||
} else {
|
||||
prose.append(lines[i]).append('\n')
|
||||
}
|
||||
i++
|
||||
continue
|
||||
}
|
||||
flushProse()
|
||||
val fence = open.groupValues[1]
|
||||
val language = open.groupValues[2]
|
||||
val page = if (pages) PAGE_OPENING.matchEntire(lines[i]) else null
|
||||
val closing = Regex("^ {0,3}${Regex.escape(fence.substring(0, 1))}{${fence.length},}\\s*$")
|
||||
val code = mutableListOf<String>()
|
||||
i++
|
||||
@@ -52,7 +97,7 @@ fun splitFences(markdown: String): List<Segment> {
|
||||
code += lines[i]
|
||||
i++
|
||||
}
|
||||
out += Segment.Code(language, code.joinToString("\n"), closed)
|
||||
out += if (page != null) Segment.Page(pageTitle(page.groupValues[1]), closed) else Segment.Code(language, code.joinToString("\n"), closed)
|
||||
}
|
||||
flushProse()
|
||||
return out
|
||||
|
||||
@@ -63,6 +63,9 @@ fun progressWords(resources: Resources): ProgressWords = ProgressWords { key, ar
|
||||
PROGRESS_STRINGS[key]?.let { id -> if (args.isEmpty()) resources.getString(id) else resources.getString(id, *args) }
|
||||
}
|
||||
|
||||
/** The end of a progress line: the shared `progress.line` separator and [clock], without the text before it. */
|
||||
fun progressClock(resources: Resources, clock: String): String = resources.getString(R.string.progress_line, "", clock)
|
||||
|
||||
/** The clock a progress line ticks by: now, again on every whole second. */
|
||||
@Composable
|
||||
fun rememberTick(): Long {
|
||||
@@ -115,7 +118,8 @@ fun ProgressStatus(progress: Progress?, status: String, style: TextStyle, color:
|
||||
}
|
||||
Row(modifier, verticalAlignment = Alignment.Top) {
|
||||
Text(text, style = style, color = color, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
|
||||
// The spec's separator, `progress.line`'s " · ", before the clock.
|
||||
if (clock != null) Text(" · $clock", style = style, color = color, maxLines = 1, softWrap = false)
|
||||
// The clock after the shared separator: `progress.line` (`{{text}} · {{elapsed}}`) with
|
||||
// the text left out, so the separator is the spec's and not a copy of it.
|
||||
if (clock != null) Text(progressClock(LocalContext.current.resources, clock), style = style, color = color, maxLines = 1, softWrap = false)
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,7 @@ import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.api.took
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
@@ -97,7 +98,8 @@ fun ToolCallBlock(call: ToolCall, depth: Int = 0, onShow: ((ShowCard) -> Unit)?
|
||||
Icon(iconFor(call.block.kind), contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkMuted)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
call.block.title.ifBlank { call.name },
|
||||
// The one short title; a call without one is named as a person reads the tool.
|
||||
call.block.title.ifBlank { call.block.label.ifBlank { call.name } },
|
||||
fontFamily = if (call.block.kind == "shell") FontFamily.Monospace else null,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = if (open) 6 else 1,
|
||||
@@ -107,6 +109,10 @@ fun ToolCallBlock(call: ToolCall, depth: Int = 0, onShow: ((ShowCard) -> Unit)?
|
||||
call.block.chips.forEach { chip ->
|
||||
Text(chip, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
// How long a finished call took (display.md §2); a running or a denied one shows none.
|
||||
call.took()?.let { took ->
|
||||
Text(took, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, maxLines = 1, modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
}
|
||||
call.purpose?.takeIf { it.isNotBlank() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
|
||||
@@ -37,6 +37,7 @@ import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.CardItem
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.Plan
|
||||
import eu.llembas.android.api.showsDetail
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
/** The sentinel the web card's "Something else" row submits (`interaction.OTHER`). */
|
||||
@@ -58,6 +59,7 @@ fun CardSheet(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
}
|
||||
when (card.kind) {
|
||||
"approval" -> Approval(card, onAnswer)
|
||||
"phone_action" -> PhoneCard(card, onAnswer)
|
||||
"plan" -> PlanCard(card, onAnswer)
|
||||
else -> Questions(card, onAnswer)
|
||||
}
|
||||
@@ -72,6 +74,7 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
var refusing by remember { mutableStateOf(false) }
|
||||
Text(stringResource(R.string.card_approval), style = MaterialTheme.typography.titleMedium)
|
||||
card.items.forEach { item ->
|
||||
val views = diffViews(item.diffs)
|
||||
// A subagent asks, not the chat's own turn: said first, as the page says it.
|
||||
val subagent = item.subagent
|
||||
if (subagent != null) {
|
||||
@@ -99,9 +102,12 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
if (approvalTexts(listOf(item), edits).isNotEmpty()) {
|
||||
Text(stringResource(R.string.card_edit_runs), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
} else if (item.detail.isNotBlank()) {
|
||||
} else if (item.detail.isNotBlank() && showsDetail(item, views)) {
|
||||
Text(item.detail, fontFamily = FontFamily.Monospace)
|
||||
}
|
||||
// An edit says what it would change: the diff stands where the call's arguments would,
|
||||
// as text. Diffs that say nothing (the same text twice) leave the arguments in view.
|
||||
if (item.diffs.isNotEmpty()) CardDiffs(item.diffs, views)
|
||||
if (item.reason.isNotBlank()) Text(item.reason, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
}
|
||||
// A corrected command goes with an allow, never with a refusal, and only when it was corrected.
|
||||
@@ -120,10 +126,15 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
} else {
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = { onAnswer(CardAnswer(verdict = "allow", texts = texts)) }) { Text(stringResource(R.string.card_allow_once)) }
|
||||
OutlinedButton(onClick = { onAnswer(CardAnswer(verdict = "allow_always", texts = texts)) }) {
|
||||
Text(stringResource(R.string.card_allow_always))
|
||||
// Only where the request offers it: a call that may only ever be allowed once has none.
|
||||
if (offersAlways(card)) {
|
||||
OutlinedButton(onClick = { onAnswer(CardAnswer(verdict = "allow_always", texts = texts)) }) {
|
||||
Text(stringResource(R.string.card_allow_always))
|
||||
}
|
||||
}
|
||||
TextButton(onClick = { refusing = true }) { Text(stringResource(R.string.card_deny)) }
|
||||
// The spec's four actions (display.md §5): Deny at once, or with the person's words to the model.
|
||||
TextButton(onClick = { onAnswer(CardAnswer(verdict = "deny")) }) { Text(stringResource(R.string.card_deny)) }
|
||||
TextButton(onClick = { refusing = true }) { Text(stringResource(R.string.card_deny_reason)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -203,20 +214,11 @@ private fun toggle(item: CardItem, now: Set<String>?, label: String): Set<String
|
||||
@Composable
|
||||
private fun PlanCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val item = card.items.firstOrNull() ?: return
|
||||
var mode by remember { mutableStateOf("edit") }
|
||||
var revising by remember { mutableStateOf(false) }
|
||||
var feedback by remember { mutableStateOf("") }
|
||||
val plan = item.plan?.let { runCatching { LembasJson.decodeFromJsonElement(Plan.serializer(), it) }.getOrNull() }
|
||||
Text(plan?.title?.ifBlank { null } ?: item.title, style = MaterialTheme.typography.titleMedium)
|
||||
plan?.let { PlanBody(it) }
|
||||
if (item.modeChoice) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
RadioButton(selected = mode == "edit", onClick = { mode = "edit" })
|
||||
Text(stringResource(R.string.mode_edit))
|
||||
RadioButton(selected = mode == "manual", onClick = { mode = "manual" })
|
||||
Text(stringResource(R.string.mode_manual))
|
||||
}
|
||||
}
|
||||
if (revising) {
|
||||
OutlinedTextField(
|
||||
value = feedback,
|
||||
@@ -226,15 +228,27 @@ private fun PlanCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
)
|
||||
Button(onClick = { onAnswer(CardAnswer(verdict = "deny", reason = feedback)) }) { Text(stringResource(R.string.card_send)) }
|
||||
} else {
|
||||
// Approve together with the mode the work continues in (display.md §5), where the
|
||||
// session may choose one; otherwise Approve alone. And Revise.
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = {
|
||||
onAnswer(CardAnswer(verdict = "allow", choices = if (item.modeChoice) mapOf(item.key to listOf(mode)) else emptyMap()))
|
||||
}) { Text(stringResource(R.string.plan_approve)) }
|
||||
OutlinedButton(onClick = { revising = true }) { Text(stringResource(R.string.plan_revise)) }
|
||||
if (item.modeChoice) {
|
||||
Button(onClick = { onAnswer(planApproval(item, "edit")) }) { Text(stringResource(R.string.plan_approve_edit)) }
|
||||
OutlinedButton(onClick = { onAnswer(planApproval(item, "manual")) }) { Text(stringResource(R.string.plan_approve_manual)) }
|
||||
} else {
|
||||
Button(onClick = { onAnswer(planApproval(item, null)) }) { Text(stringResource(R.string.plan_approve)) }
|
||||
}
|
||||
TextButton(onClick = { revising = true }) { Text(stringResource(R.string.plan_revise)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether an approval card offers "Always allow": only when every call on it may be remembered (`always`). */
|
||||
internal fun offersAlways(card: Card): Boolean = card.items.isNotEmpty() && card.items.all { it.always }
|
||||
|
||||
/** A plan's approval as the server reads it: allow, and the mode to continue in where one was chosen. */
|
||||
internal fun planApproval(item: CardItem, mode: String?): CardAnswer =
|
||||
CardAnswer(verdict = "allow", choices = if (item.modeChoice && mode != null) mapOf(item.key to listOf(mode)) else emptyMap())
|
||||
|
||||
/** A plan's phases and tasks, ticked as the reply works through them. */
|
||||
@Composable
|
||||
fun PlanBody(plan: Plan) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import android.os.Build
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.gestures.scrollBy
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.interaction.DragInteraction
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
@@ -35,6 +36,7 @@ import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Archive
|
||||
import androidx.compose.material.icons.filled.Bolt
|
||||
import androidx.compose.material.icons.filled.ChatBubbleOutline
|
||||
@@ -77,9 +79,11 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
@@ -90,12 +94,29 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.Drawn
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaView
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.api.drawn
|
||||
import eu.llembas.android.api.editable
|
||||
import eu.llembas.android.api.unrecordedReplies
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.ProgressStatus
|
||||
import eu.llembas.android.ui.files.TransferHost
|
||||
import eu.llembas.android.ui.files.TransferViewModel
|
||||
import eu.llembas.android.ui.files.rememberSaver
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.DocumentDialog
|
||||
import eu.llembas.android.ui.viewer.FileViewer
|
||||
import eu.llembas.android.ui.viewer.PlayerDialog
|
||||
import eu.llembas.android.ui.viewer.Playing
|
||||
import eu.llembas.android.ui.viewer.Reading
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
@@ -112,6 +133,10 @@ fun ChatScreen(
|
||||
onOpened: (String) -> Unit = {},
|
||||
agent: Boolean = false,
|
||||
onKind: ((agent: Boolean) -> Unit)? = null,
|
||||
/** Entered from a report (its Reply): the bar says "Report: title" and has Back, to the report, where the menu is. */
|
||||
report: String? = null,
|
||||
/** Open the person's Files at a folder: where a generated file's "Open in Files" leads. */
|
||||
onFiles: (String) -> Unit = {},
|
||||
model: ChatViewModel = viewModel(key = chatId ?: if (agent) "new-agent" else "new"),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
@@ -129,6 +154,17 @@ fun ChatScreen(
|
||||
LaunchedEffect(state.chat?.id) {
|
||||
if (state.chat?.id != null) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchActivity() }
|
||||
}
|
||||
// The chat's long generations (a video, a track), read again every few seconds while the
|
||||
// screen is in front and not otherwise. An agent chat runs on a computer and makes none.
|
||||
LaunchedEffect(state.chat?.id) {
|
||||
if (state.chat?.id != null && !isAgent) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchMedia() }
|
||||
}
|
||||
// Replies nobody asked for from this screen (a subagent that woke the main agent, a schedule,
|
||||
// a turn the linked computer started): heard on the person's events route while the screen is
|
||||
// in front, and caught up with once on every return to it.
|
||||
LaunchedEffect(state.chat?.id) {
|
||||
if (state.chat?.id != null) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchReplies() }
|
||||
}
|
||||
LaunchedEffect(state.error, state.notice) {
|
||||
(state.error ?: state.notice)?.let {
|
||||
snackbar.showSnackbar(it)
|
||||
@@ -136,10 +172,51 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// What a generated file's card does: the player over the chat, the folder in Files, and the
|
||||
// ways a file leaves the app. Its own transfers, as each screen that hands files out has.
|
||||
val transfers: TransferViewModel = viewModel(key = "chat-transfers")
|
||||
val saveTo = rememberSaver(transfers)
|
||||
var playing by remember { mutableStateOf<Playing?>(null) }
|
||||
var reading by remember { mutableStateOf<Reading?>(null) }
|
||||
val media = remember(model, transfers) {
|
||||
object : MediaActions {
|
||||
override fun play(media: GeneratedMedia) {
|
||||
playing = Playing(media.raw, media.title, media.size, video = media.view == MediaView.Video)
|
||||
}
|
||||
|
||||
override fun play(attachment: Attachment) {
|
||||
playing = Playing(Raw.Attached(attachment.id), attachment.name, attachment.size, video = attachment.kind == "video")
|
||||
}
|
||||
|
||||
override fun view(media: GeneratedMedia) {
|
||||
reading = Reading(media.raw, media.title, media.size)
|
||||
}
|
||||
|
||||
// Where the file is now, by its id: it may have been renamed or moved since it was made.
|
||||
override fun openInFiles(media: GeneratedMedia) = model.whereIs(media, onFiles)
|
||||
|
||||
override fun download(media: GeneratedMedia) = saveTo(media.raw, media.title, media.mime)
|
||||
|
||||
override fun share(media: GeneratedMedia) = transfers.share(media.raw, media.title, media.mime)
|
||||
|
||||
override fun openWith(media: GeneratedMedia) = transfers.openWith(media.raw, media.title)
|
||||
|
||||
override fun cancel(job: MediaJob) = model.cancelJob(job)
|
||||
}
|
||||
}
|
||||
|
||||
// Read aloud on a reply, when the instance has a voice; it stops when the chat is left.
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val readAloud = remember { ReadAloud(context, scope) { said -> scope.launch { snackbar.showSnackbar(said) } } }
|
||||
val readAloud = remember {
|
||||
ReadAloud(
|
||||
context,
|
||||
scope,
|
||||
media = { model.state.value.mediaFor },
|
||||
onFallback = { source -> model.mediaFellBack(MEDIA_SPEECH, context.getString(R.string.read_by_fallback, source)) },
|
||||
onError = { said -> scope.launch { snackbar.showSnackbar(said) } },
|
||||
)
|
||||
}
|
||||
LaunchedEffect(Unit) { readAloud.load() }
|
||||
DisposableEffect(Unit) { onDispose { readAloud.stop() } }
|
||||
|
||||
@@ -155,6 +232,8 @@ fun ChatScreen(
|
||||
onActivity = { activityOpen = true },
|
||||
onShow = { showing = it },
|
||||
onKind = onKind,
|
||||
report = report,
|
||||
media = media,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -165,8 +244,15 @@ fun ChatScreen(
|
||||
showing?.let { file ->
|
||||
state.chat?.id?.let { id -> FileViewer(id, file, onClose = { showing = null }) }
|
||||
}
|
||||
playing?.let { PlayerDialog(it, onClose = { playing = null }, gone = stringResource(R.string.media_gone)) }
|
||||
reading?.let { DocumentDialog(it, onClose = { reading = null }, gone = stringResource(R.string.media_gone)) }
|
||||
TransferHost(transfers)
|
||||
}
|
||||
|
||||
/** What the bar says of a chat entered from a report: "Report: title", or "Report" when the title is not known. */
|
||||
@Composable
|
||||
private fun reportTitle(title: String): String = if (title.isBlank()) stringResource(R.string.report) else stringResource(R.string.report_chat_title, title)
|
||||
|
||||
/**
|
||||
* The chat as it is drawn, from [state] alone: what the screenshot tests render with fake data.
|
||||
* Everything it does goes through [actions].
|
||||
@@ -183,10 +269,14 @@ fun ChatContent(
|
||||
onActivity: () -> Unit = {},
|
||||
onShow: (ShowCard) -> Unit = {},
|
||||
onKind: ((agent: Boolean) -> Unit)? = null,
|
||||
report: String? = null,
|
||||
/** What the cards of generated media do; null draws none of them (a picture stays a picture). */
|
||||
media: MediaActions? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val chatMedia = remember(state.mediaJobs, media) { media?.let { ChatMedia(state.mediaJobs, it) } }
|
||||
// A chat opens at its end, where the conversation is, not at its first message.
|
||||
val list = rememberLazyListState(initialFirstVisibleItemIndex = maxOf(0, state.messages.size - 1 + if (state.more) 1 else 0))
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
@@ -194,6 +284,7 @@ fun ChatContent(
|
||||
var tuning by remember { mutableStateOf(false) }
|
||||
var renaming by remember { mutableStateOf(false) }
|
||||
var editing by remember { mutableStateOf<Message?>(null) }
|
||||
var discarding by remember { mutableStateOf<Message?>(null) }
|
||||
var suggestion by remember { mutableStateOf("") }
|
||||
var suggested by remember { mutableIntStateOf(0) }
|
||||
val copy: (String) -> Unit = { text ->
|
||||
@@ -205,18 +296,81 @@ fun ChatContent(
|
||||
val live = state.live
|
||||
val rows = state.messages
|
||||
val info = state.modelInfo
|
||||
// Only in an agent chat: there a turn's reply is the linked computer's, and may never have been written here.
|
||||
val unrecorded = remember(rows, chat?.isAgent, live?.messageId) { if (chat?.isAgent == true) unrecordedReplies(rows, live?.messageId) else emptySet() }
|
||||
|
||||
// To the end when the transcript grows, and while a reply is being written -- but only if
|
||||
// the person is at the end already: reading back up is not interrupted by the next line.
|
||||
var following by remember { mutableStateOf(true) }
|
||||
LaunchedEffect(list.isScrollInProgress) {
|
||||
if (!list.isScrollInProgress) following = !list.canScrollForward
|
||||
// The view keeps to the end while a reply is written only for a person who is there
|
||||
// (`Follow.kt` has the rule): a finger on the list ends the following at once, and where the
|
||||
// list comes to rest says whether it is taken up again. Kept over a rotation, with the place.
|
||||
var following by rememberSaveable { mutableStateOf(true) }
|
||||
var drawnBefore by rememberSaveable { mutableStateOf(false) }
|
||||
val slack = with(LocalDensity.current) { 48.dp.roundToPx() }
|
||||
// Whether a finger has been on the list since it last came to rest.
|
||||
val touched = remember { booleanArrayOf(false) }
|
||||
// How many of this app's own scrolls are under way (`ownScroll`): any other scroll is the person's.
|
||||
val own = remember { intArrayOf(0) }
|
||||
// The model drops the far end of a long transcript only under a person who is at its end.
|
||||
LaunchedEffect(following) { actions.reading(atEnd = following) }
|
||||
LaunchedEffect(list) {
|
||||
list.interactionSource.interactions.collect {
|
||||
if (it is DragInteraction.Start) {
|
||||
touched[0] = true
|
||||
following = false
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(list) {
|
||||
var moving = false
|
||||
var fromIndex = list.firstVisibleItemIndex
|
||||
var fromOffset = list.firstVisibleItemScrollOffset
|
||||
var startedByApp = false
|
||||
snapshotFlow { list.isScrollInProgress }.collect { now ->
|
||||
if (now && !moving) {
|
||||
fromIndex = list.firstVisibleItemIndex
|
||||
fromOffset = list.firstVisibleItemScrollOffset
|
||||
startedByApp = own[0] > 0
|
||||
}
|
||||
if (moving && !now) {
|
||||
// Only the person's own scroll ends the following (`restFollows`): this app's
|
||||
// scroll to the end, overtaken by a line that arrived meanwhile, does not.
|
||||
val byPerson = scrollWasPersons(
|
||||
touched = touched[0],
|
||||
wentBack = wentBack(fromIndex, fromOffset, list.firstVisibleItemIndex, list.firstVisibleItemScrollOffset),
|
||||
startedByApp = startedByApp,
|
||||
)
|
||||
following = restFollows(following, byPerson, list.distanceToEnd(), slack)
|
||||
touched[0] = false
|
||||
}
|
||||
moving = now
|
||||
}
|
||||
}
|
||||
// The rows as they were at the last draw, to tell a message sent from an older page loaded.
|
||||
val known = remember { arrayOfNulls<List<Message>>(1) }
|
||||
LaunchedEffect(rows) {
|
||||
val before = known[0]
|
||||
known[0] = rows
|
||||
val change = transcriptChange(before, rows, restored = drawnBefore, sent = state.lastSent)
|
||||
if (rows.isNotEmpty()) drawnBefore = true
|
||||
if (change == TranscriptChange.Older) {
|
||||
// An older page above the very top: the row that was first stays first, so reading
|
||||
// goes on upwards from it. Anywhere else the list keeps its place by the rows' keys.
|
||||
val kept = keptRow(before.orEmpty(), rows)
|
||||
if (kept != null && list.firstVisibleItemIndex == 0) ownScroll(own) { list.scrollToItem(kept + if (state.more) 1 else 0) }
|
||||
} else if (movesToEnd(change, following, personScrolls(list.isScrollInProgress, own[0]))) {
|
||||
// A list the person is moving is left to them: where it rests says whether it follows.
|
||||
following = true
|
||||
ownScroll(own) { list.toEnd() }
|
||||
}
|
||||
}
|
||||
LaunchedEffect(rows.size) { if (rows.isNotEmpty()) list.toEnd() }
|
||||
val growth = live?.let { it.shown.size * 100_000 + (it.tail.text.length + it.tail.thinking.length) } ?: 0
|
||||
LaunchedEffect(growth) { if (growth > 0 && following) list.toEnd() }
|
||||
LaunchedEffect(growth) { if (growth > 0 && following && !list.isScrollInProgress) ownScroll(own) { list.toEnd() } }
|
||||
// The keyboard opening takes the list's foot away: a person at the end stays at the end.
|
||||
LaunchedEffect(list) {
|
||||
// A finger on the list ends a scroll of ours by cancelling it: this follower goes on.
|
||||
snapshotFlow { list.layoutInfo.viewportSize.height }.drop(1).collect { if (following && !list.isScrollInProgress) ownScroll(own) { list.toEnd() } }
|
||||
}
|
||||
|
||||
CompositionLocalProvider(LocalCopy provides copy) {
|
||||
CompositionLocalProvider(LocalCopy provides copy, LocalChatMedia provides chatMedia) {
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
@@ -224,13 +378,24 @@ fun ChatContent(
|
||||
TopAppBar(
|
||||
colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg, scrolledContainerColor = palette.bg),
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onMenu) { Icon(Icons.Filled.Menu, contentDescription = stringResource(R.string.chats_open)) }
|
||||
if (report != null) {
|
||||
// A report's conversation is reached from the report, and Back returns there.
|
||||
IconButton(onClick = onMenu) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
} else {
|
||||
IconButton(onClick = onMenu) { Icon(Icons.Filled.Menu, contentDescription = stringResource(R.string.chats_open)) }
|
||||
}
|
||||
},
|
||||
title = {
|
||||
ModelTitle(
|
||||
model = info,
|
||||
fallback = state.modelId ?: stringResource(R.string.app_name),
|
||||
subtitle = chat?.title?.ifBlank { null },
|
||||
fallback = state.modelWord ?: stringResource(R.string.app_name),
|
||||
// A report's conversation says which report: by what it was entered with, else by
|
||||
// what the chat itself says (after the app was closed in between).
|
||||
subtitle = if (report != null || chat?.report != null) {
|
||||
reportTitle(report?.ifBlank { null } ?: chat?.report?.title.orEmpty())
|
||||
} else {
|
||||
chat?.title?.ifBlank { null }
|
||||
},
|
||||
onClick = { picking = true },
|
||||
)
|
||||
},
|
||||
@@ -250,10 +415,13 @@ fun ChatContent(
|
||||
menu = false
|
||||
actions.continueChat()
|
||||
}
|
||||
MenuItem(Icons.Filled.Archive, stringResource(R.string.archive)) {
|
||||
menu = false
|
||||
actions.change("archived", "true")
|
||||
onLeave()
|
||||
// Only what may be done to this chat: a report's conversation is not archived.
|
||||
if (chat.allows("archive")) {
|
||||
MenuItem(Icons.Filled.Archive, stringResource(R.string.archive)) {
|
||||
menu = false
|
||||
actions.change("archived", "true")
|
||||
onLeave()
|
||||
}
|
||||
}
|
||||
MenuItem(Icons.Filled.Delete, stringResource(R.string.delete)) {
|
||||
menu = false
|
||||
@@ -334,20 +502,44 @@ fun ChatContent(
|
||||
item { TextButton(onClick = actions::older) { Text(stringResource(R.string.older)) } }
|
||||
}
|
||||
items(rows, key = { it.id }) { message ->
|
||||
when {
|
||||
message.isUser -> UserMessage(message, canEdit = !message.machine && live == null, onEdit = { editing = message })
|
||||
// One key for a reply while it is written and once it is stored: the row
|
||||
// is the same row at `done`, so the list has nothing to put elsewhere.
|
||||
// The first row is the chat's first message only once nothing older is left to load.
|
||||
val first = !state.more && message.id == rows.firstOrNull()?.id
|
||||
when (drawn(message, first, reportChat = report != null || chat?.report != null)) {
|
||||
// The server's own line in the person's place: nothing, or a note.
|
||||
Drawn.Hidden -> Unit
|
||||
|
||||
live != null && live.messageId == message.id && live.finished == null ->
|
||||
AssistantMessage(message, live.shown, writing = true, canRegenerate = false, onRegenerate = {}, onShow = onShow)
|
||||
Drawn.Note -> MachineNote(message.text.orEmpty())
|
||||
|
||||
else -> AssistantMessage(
|
||||
// A message that waits is sent now or discarded, never edited.
|
||||
Drawn.Person -> UserMessage(
|
||||
message,
|
||||
message.steps,
|
||||
writing = false,
|
||||
canRegenerate = live == null && message == rows.lastOrNull(),
|
||||
onRegenerate = { actions.regenerate(message) },
|
||||
onShow = onShow,
|
||||
canEdit = message.editable(writing = live != null),
|
||||
onEdit = { editing = message },
|
||||
busy = state.acting != null,
|
||||
onSendNow = { actions.sendNow(message) },
|
||||
onDiscard = { discarding = message },
|
||||
)
|
||||
|
||||
// One call for a reply being written and the same reply finished:
|
||||
// what the person opened in it (a thinking chip) stays open at `done`.
|
||||
// A finished reply with nothing in it, after a turn nobody typed: one
|
||||
// quiet line in its place, not a blank row with buttons.
|
||||
Drawn.Reply -> if (message.id in unrecorded) {
|
||||
MachineNote(stringResource(R.string.reply_unrecorded))
|
||||
} else {
|
||||
val writing = live?.takeIf { it.messageId == message.id && it.finished == null }
|
||||
AssistantMessage(
|
||||
message,
|
||||
writing?.shown ?: message.steps,
|
||||
writing = writing != null,
|
||||
canRegenerate = live == null && message == rows.lastOrNull(),
|
||||
onRegenerate = { actions.regenerate(message) },
|
||||
onShow = onShow,
|
||||
models = state.models,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -357,7 +549,7 @@ fun ChatContent(
|
||||
|
||||
if (picking) {
|
||||
ModalBottomSheet(onDismissRequest = { picking = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
|
||||
ModelPickerContent(state.models, state.modelId, onPick = { id ->
|
||||
ModelPickerContent(state.models, state.modelInfo?.key, onPick = { id ->
|
||||
picking = false
|
||||
if (chat == null) actions.updateDraft { it.copy(model = id) } else actions.change("model", id)
|
||||
})
|
||||
@@ -397,6 +589,21 @@ fun ChatContent(
|
||||
)
|
||||
}
|
||||
|
||||
// Discarding cannot be taken back, so it is asked once -- in the page's own words.
|
||||
discarding?.let { message ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { discarding = null },
|
||||
text = { Text(stringResource(R.string.discard_message_confirm)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
actions.discard(message)
|
||||
discarding = null
|
||||
}) { Text(stringResource(R.string.discard)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { discarding = null }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
editing?.let { message ->
|
||||
var text by remember(message.id) { mutableStateOf(message.text.orEmpty()) }
|
||||
AlertDialog(
|
||||
@@ -427,6 +634,14 @@ private suspend fun LazyListState.toEnd() {
|
||||
scrollBy(1_000_000f)
|
||||
}
|
||||
|
||||
/** How far the list stands from its very end, in pixels; a last row not on screen is "far". */
|
||||
private fun LazyListState.distanceToEnd(): Int {
|
||||
val info = layoutInfo
|
||||
val last = info.visibleItemsInfo.lastOrNull() ?: return 0
|
||||
if (last.index < info.totalItemsCount - 1) return Int.MAX_VALUE
|
||||
return last.offset + last.size + info.afterContentPadding - info.viewportEndOffset
|
||||
}
|
||||
|
||||
/**
|
||||
* A new chat's empty page: what kind of chat it is ([onKind], Chat or Agent, one line each), then
|
||||
* the model's picture and a greeting. A new agent chat says where it will run instead, and that
|
||||
@@ -480,7 +695,7 @@ private fun Greeting(
|
||||
}
|
||||
TextButton(onClick = onTune) { Text(where, textAlign = TextAlign.Center, color = palette.inkMuted) }
|
||||
} else {
|
||||
ModelAvatar(state.modelInfo, state.modelId ?: "?", size = 64.dp)
|
||||
ModelAvatar(state.modelInfo, state.modelWord ?: "?", size = 64.dp)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Text(stringResource(R.string.empty_chat), style = MaterialTheme.typography.headlineSmall, textAlign = TextAlign.Center)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import android.provider.OpenableColumns
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Activity
|
||||
import eu.llembas.android.api.ActivityAgent
|
||||
import eu.llembas.android.api.ActivityFrame
|
||||
@@ -20,21 +21,40 @@ import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ChatDetail
|
||||
import eu.llembas.android.api.DeviceDirectory
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.MediaFor
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.Mention
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.MessagePage
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.ReplyFrame
|
||||
import eu.llembas.android.api.StartModel
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.SubagentTree
|
||||
import eu.llembas.android.api.Turn
|
||||
import eu.llembas.android.api.Whereabouts
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.api.serving
|
||||
import eu.llembas.android.api.whereabouts
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.files.noSuchRoute
|
||||
import eu.llembas.android.whileOpen
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.takeWhile
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -81,6 +101,22 @@ data class ChatState(
|
||||
val tree: SubagentTree? = null,
|
||||
/** For a new agent chat: whether it may have subagents, and whether its device runs them. */
|
||||
val agentSubagents: AgentSubagents? = null,
|
||||
/**
|
||||
* For a new agent chat: the model it starts on in the chosen device and folder when the
|
||||
* person picks none (spec 3.9.0) -- the folder's usual model, as the instance asked the
|
||||
* device. Shown, never sent and never kept: the instance does the same on its own.
|
||||
*/
|
||||
val start: StartModel? = null,
|
||||
/** What `@` offers for the word being typed: the server's files, earlier attachments and pages, or an agent chat's device's files. */
|
||||
val mentions: List<Mention> = emptyList(),
|
||||
/** The message this app sent last, by its id: what the transcript shows whoever has scrolled where. */
|
||||
val lastSent: String? = null,
|
||||
/** The model picked for this open chat, by its ref: which of two models with one id the chat is on. */
|
||||
val picked: String? = null,
|
||||
/** The chat's long generations (a video, a track, a 3D model), by id, as each was last read. */
|
||||
val mediaJobs: Map<String, JobSeen> = emptyMap(),
|
||||
/** The waiting message that is being sent now or discarded, by its id, until the instance has answered. */
|
||||
val acting: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -102,11 +138,58 @@ data class Draft(
|
||||
/** The one tool a message may force (the server's `FORCEABLE_TOOLS`): make a picture. */
|
||||
const val IMAGE_TOOL = "image_generate"
|
||||
|
||||
/** The model in force: the chat's, else the one chosen for the new chat, else the default. */
|
||||
/**
|
||||
* The model in force: the chat's, else the one chosen for the new chat, else the folder's usual
|
||||
* one (a new agent chat's, where the person still has it), else the default. A model the
|
||||
* person picked is never set aside by the folder's.
|
||||
*/
|
||||
val ChatState.modelId: String?
|
||||
get() = chat?.model?.ifBlank { null } ?: draft.model ?: models.firstOrNull { it.default }?.id ?: models.firstOrNull()?.id
|
||||
get() = chatModel ?: draft.model ?: folderModel ?: models.firstOrNull { it.default }?.key ?: models.firstOrNull()?.key
|
||||
|
||||
val ChatState.modelInfo: ModelInfo? get() = models.firstOrNull { it.id == modelId }
|
||||
/**
|
||||
* An open chat's model: the connection the chat itself names (`model_ref`), where the server
|
||||
* says it. From an older server the chat says only its model's id, which two connections may
|
||||
* share; the one picked here ([ChatState.picked], a ref) then says which of them, for as long
|
||||
* as the chat is still on a model of that id.
|
||||
*/
|
||||
val ChatState.chatModel: String?
|
||||
get() {
|
||||
chat?.modelRef?.ifBlank { null }?.let { return it }
|
||||
val served = chat?.model?.ifBlank { null } ?: return null
|
||||
return picked?.takeIf { models.named(it)?.id == served } ?: served
|
||||
}
|
||||
|
||||
/** The folder's usual model for a chat not made yet, when it is one of the models offered here. */
|
||||
val ChatState.folderModel: String?
|
||||
get() = start?.takeIf { chat == null }?.let { models.named(it.key) ?: models.named(it.model) }?.key
|
||||
|
||||
/** The model in force, among the models offered: a chat that names its connection is on that one or on none of them. */
|
||||
val ChatState.modelInfo: ModelInfo?
|
||||
get() {
|
||||
val ref = chat?.modelRef?.ifBlank { null } ?: return models.named(modelId)
|
||||
return models.serving(ref, chat?.model)
|
||||
}
|
||||
|
||||
/** What the model in force is called where the list does not have it: the chat's own id for it, not its ref. */
|
||||
val ChatState.modelWord: String?
|
||||
get() = chat?.takeIf { !it.modelRef.isNullOrBlank() }?.model?.ifBlank { null } ?: modelId
|
||||
|
||||
/**
|
||||
* Which chat a dictation or a reply read aloud is for: this chat once it exists, else the model
|
||||
* a new one would be on -- so the instance can serve it from that model's connection.
|
||||
*/
|
||||
val ChatState.mediaFor: MediaFor get() = MediaFor.of(chat?.id, modelId)
|
||||
|
||||
/** The two things a chat asks the instance's speech for, each with its own one note of a fallback. */
|
||||
const val MEDIA_DICTATION = "dictation"
|
||||
const val MEDIA_SPEECH = "speech"
|
||||
|
||||
/**
|
||||
* Whether a fallback of [kind] is still to be said, given what was [told]: once per kind for as
|
||||
* long as the chat is open. A connection's speech model that is down stays down for a while,
|
||||
* and the same sentence after every dictation is noise.
|
||||
*/
|
||||
fun fallbackToSay(told: Set<String>, kind: String): Boolean = kind !in told
|
||||
|
||||
/** The thinking level in force, by the model's levels; null for a model with no choice. */
|
||||
val ChatState.level: String?
|
||||
@@ -145,6 +228,82 @@ val ChatState.running: Boolean get() = live != null && live.finished == null
|
||||
/** The linked device a new agent chat runs on: the chosen one, else the first. */
|
||||
val ChatState.device: LinkedDevice? get() = devices.firstOrNull { it.id == draft.device } ?: devices.firstOrNull()
|
||||
|
||||
/**
|
||||
* An older [page], read before the message [before], put above the transcript. Only while
|
||||
* [before] is still the first row -- a transcript read again meanwhile has moved, and the page
|
||||
* no longer belongs above it -- and never a row twice: the list's rows are keyed by id, and a
|
||||
* key drawn twice ends the app.
|
||||
*/
|
||||
fun ChatState.withOlder(before: String, page: MessagePage): ChatState {
|
||||
if (messages.firstOrNull()?.id != before) return this
|
||||
val have = messages.mapTo(HashSet()) { it.id }
|
||||
return copy(messages = page.messages.distinctBy { it.id }.filterNot { it.id in have } + messages, more = page.more)
|
||||
}
|
||||
|
||||
/**
|
||||
* The transcript read again ([read]: the chat and its newest page), put where the newest page
|
||||
* was. The older pages a person loaded stay above it -- taking them away would take the row
|
||||
* they are reading from under them -- as long as the page still joins them: its first row is
|
||||
* one this screen holds, and the server says there is more above it. A page that joins nothing
|
||||
* here (the chat was rewound past it, or compacted) is the whole transcript, as before. No row
|
||||
* is there twice: the list's rows are keyed by id.
|
||||
*/
|
||||
fun ChatState.withNewest(read: ChatDetail): ChatState {
|
||||
val first = read.messages.firstOrNull()?.id
|
||||
val at = if (first == null) -1 else messages.indexOfFirst { it.id == first }
|
||||
if (at <= 0 || !read.more) return copy(chat = read.chat, messages = read.messages, more = read.more)
|
||||
val newest = read.messages.mapTo(HashSet()) { it.id }
|
||||
return copy(chat = read.chat, messages = messages.subList(0, at).filterNot { it.id in newest } + read.messages)
|
||||
}
|
||||
|
||||
/** Past this many rows a transcript left open is cut back to [KEPT_ROWS]: several times what a person scrolls through. */
|
||||
const val KEPT_MOST = 600
|
||||
|
||||
/** How many of the newest rows stay when a transcript is cut back. */
|
||||
const val KEPT_ROWS = 400
|
||||
|
||||
/**
|
||||
* The transcript, held to a size: a chat left open while replies arrive by themselves (an
|
||||
* agent's wakes, a schedule) would otherwise grow for as long as it is open. Past [most] rows
|
||||
* the oldest go, down to the newest [keep], and "older" is offered again, which reads them
|
||||
* back. Only for a person who is [atEnd]: someone reading further up is reading the very rows
|
||||
* that would go, and nothing is taken from under them.
|
||||
*/
|
||||
fun ChatState.capped(atEnd: Boolean, most: Int = KEPT_MOST, keep: Int = KEPT_ROWS): ChatState {
|
||||
if (!atEnd || messages.size <= most) return this
|
||||
return copy(messages = messages.takeLast(keep), more = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the events route's `reply` frame [said] is news to this screen: a reply in the chat
|
||||
* that is open here, which is neither the one being followed nor a row already drawn as
|
||||
* finished. The server says every reply that starts, this app's own too, so most frames for an
|
||||
* open chat are not news.
|
||||
*/
|
||||
fun ChatState.asksFor(said: ReplyFrame): Boolean {
|
||||
if (chat == null || chat.id != said.chatId || said.messageId.isBlank()) return false
|
||||
if (live?.messageId == said.messageId) return false
|
||||
return messages.none { it.id == said.messageId && !it.isUser && it.complete }
|
||||
}
|
||||
|
||||
/**
|
||||
* The stream of the reply [messageId] closed without a `done`. What was written stays in view:
|
||||
* the transcript as the server has it now ([reread]), or -- where that could not be read -- the
|
||||
* row with the steps the stream had shown, closed, and how it ended where the stream said so.
|
||||
* Nothing is live after it. A reply another stream is being followed for is left alone.
|
||||
*/
|
||||
fun ChatState.closedUnfinished(messageId: String, reread: ChatDetail?): ChatState {
|
||||
val was = live?.takeIf { it.messageId == messageId }
|
||||
if (live != null && was == null) return this
|
||||
if (reread != null) return withNewest(reread).copy(live = null)
|
||||
if (was == null || was.shown.isEmpty()) return copy(live = null)
|
||||
val kept = was.shown.map { it.copy(open = false) }
|
||||
return copy(
|
||||
live = null,
|
||||
messages = messages.map { if (it.id == messageId) it.copy(steps = kept, progress = it.progress ?: was.end) else it },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* What the chat screen asks of its model. Every action has a do-nothing default, so the
|
||||
* screenshot tests draw the screen with fake data and no server behind it.
|
||||
@@ -154,22 +313,46 @@ interface ChatActions {
|
||||
fun stop() {}
|
||||
fun regenerate(message: Message) {}
|
||||
fun edit(message: Message, text: String) {}
|
||||
|
||||
/** Send a message that waits ([Message.waiting]) now, as a turn with a reply of its own. */
|
||||
fun sendNow(message: Message) {}
|
||||
|
||||
/** Withdraw a message that waits: it was never given to a model, and its row goes. */
|
||||
fun discard(message: Message) {}
|
||||
fun continueChat() {}
|
||||
fun executePlan() {}
|
||||
fun answer(card: Card, answer: CardAnswer) {}
|
||||
fun change(key: String, value: String?) {}
|
||||
|
||||
/** The instance's default answered a dictation or a reading ([kind]) for the chat's own: [sentence] says so, once. */
|
||||
fun mediaFellBack(kind: String, sentence: String) {}
|
||||
|
||||
/** Something the screen asked the instance itself (a dictation) failed: said as any failure is. */
|
||||
fun failed(e: Throwable) {}
|
||||
|
||||
/** A new agent chat with no computer linked: read the linked devices again. */
|
||||
fun recheckDevices() {}
|
||||
|
||||
/** A new agent chat's device, asked for a directory (`""`: its places), for the folder picker. */
|
||||
suspend fun directories(path: String): DeviceDirectory = DeviceDirectory()
|
||||
fun setAgents(agents: AgentsSetting) {}
|
||||
fun updateDraft(change: (Draft) -> Draft) {}
|
||||
fun attach(uris: List<Uri>) {}
|
||||
|
||||
/** The `@` word being typed ([query]; null: none) -- what it offers comes to the state's `mentions`. */
|
||||
fun suggest(query: String?) {}
|
||||
|
||||
/** Attach what an `@` entry names: an earlier attachment, a file of the tree, or a page. */
|
||||
fun mention(item: Mention) {}
|
||||
fun unattach(attachment: Attachment) {}
|
||||
fun photoTarget(): Uri? = null
|
||||
fun rename(title: String) {}
|
||||
fun delete(then: () -> Unit) {}
|
||||
fun older() {}
|
||||
fun clearUnsent() {}
|
||||
|
||||
/** Whether the person is at the transcript's end ([atEnd]) or reading further up: the screen's word, for what may be dropped. */
|
||||
fun reading(atEnd: Boolean) {}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -193,7 +376,7 @@ class ChatViewModel(app: Application) :
|
||||
private fun fail(e: Throwable) {
|
||||
// A follow that was replaced by a newer one is cancelled, not failed: nothing to say.
|
||||
if (e is CancellationException) return
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e), loading = false, uploading = false) }
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e), loading = false, uploading = uploads > 0) }
|
||||
}
|
||||
|
||||
fun clearError() = _state.update { it.copy(error = null, notice = null) }
|
||||
@@ -201,20 +384,43 @@ class ChatViewModel(app: Application) :
|
||||
override fun clearUnsent() = _state.update { it.copy(unsent = null) }
|
||||
|
||||
override fun updateDraft(change: (Draft) -> Draft) {
|
||||
val before = _state.value.device?.id
|
||||
val before = _state.value.let { it.device?.id to it.draft.directory }
|
||||
_state.update { it.copy(draft = change(it.draft)) }
|
||||
if (agentChat && _state.value.chat == null && _state.value.device?.id != before) readAgentFacts()
|
||||
val after = _state.value.let { it.device?.id to it.draft.directory }
|
||||
// Another computer or another folder: its Subagents fact and its usual model are read again.
|
||||
if (agentChat && _state.value.chat == null && after != before) readAgentFacts()
|
||||
}
|
||||
|
||||
/** A new agent chat's Subagents fact, for the device chosen now; an older server says nothing. */
|
||||
/**
|
||||
* A new agent chat's facts for the device and folder chosen now: whether it may have
|
||||
* subagents, and the model it starts on there. An older server says neither; an answer for
|
||||
* a choice that has changed meanwhile is dropped.
|
||||
*/
|
||||
private fun readAgentFacts() {
|
||||
val device = _state.value.device?.id
|
||||
val directory = _state.value.draft.directory
|
||||
// What was read for another device or folder is not this one's.
|
||||
_state.update { it.copy(start = null) }
|
||||
viewModelScope.launch {
|
||||
val facts = runCatching { api().agentModelList(device) }.getOrNull()?.agentSubagents
|
||||
_state.update { if (it.device?.id == device) it.copy(agentSubagents = facts) else it }
|
||||
val list = runCatching { api().agentModelList(device, directory) }.getOrNull()
|
||||
_state.update {
|
||||
if (it.device?.id == device &&
|
||||
it.draft.directory == directory
|
||||
) {
|
||||
it.copy(agentSubagents = list?.agentSubagents, start = list?.start)
|
||||
} else {
|
||||
it
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun directories(path: String): DeviceDirectory {
|
||||
// No computer linked: there is nothing to list, and the typed path is what remains.
|
||||
val device = _state.value.device ?: return DeviceDirectory(code = "device_not_linked")
|
||||
return api().deviceDirectories(device.id, path)
|
||||
}
|
||||
|
||||
override fun rename(title: String) = change("title", title.trim())
|
||||
|
||||
/** Open a chat, or (no id) get a new one ready: an agent chat also needs the linked devices. */
|
||||
@@ -239,7 +445,8 @@ class ChatViewModel(app: Application) :
|
||||
_state.update {
|
||||
it.copy(chat = detail.chat, messages = detail.messages, more = detail.more, models = models, loading = false)
|
||||
}
|
||||
detail.live?.let { follow(it) }
|
||||
// Being written when the chat was opened: whoever started it, nobody asked for it from here just now.
|
||||
detail.live?.let { follow(it, own = false) }
|
||||
// Whether a team is offered and what runs in the background: the cheap read,
|
||||
// without the context count. A server without the panel has no answer.
|
||||
runCatching { client.activity(chatId, context = false) }.onSuccess { a ->
|
||||
@@ -263,70 +470,191 @@ class ChatViewModel(app: Application) :
|
||||
}
|
||||
}
|
||||
|
||||
private var olderRead: Job? = null
|
||||
|
||||
/** The page before the first row. One read at a time: a second tap while one is under way is not a second page. */
|
||||
override fun older() {
|
||||
if (olderRead?.isActive == true) return
|
||||
val chat = _state.value.chat ?: return
|
||||
val first = _state.value.messages.firstOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
olderRead = viewModelScope.launch {
|
||||
runCatching { api().messages(chat.id, first.id) }
|
||||
.onSuccess { page -> _state.update { it.copy(messages = page.messages + it.messages, more = page.more) } }
|
||||
.onSuccess { page -> _state.update { it.withOlder(first.id, page) } }
|
||||
.onFailure(::fail)
|
||||
}
|
||||
}
|
||||
|
||||
/** Follow a reply to its end, then whatever the queue started after it. */
|
||||
private fun follow(messageId: String) {
|
||||
private val gate get() = getApplication<Application>().lembas.gate
|
||||
|
||||
/** The transcript's reads, one at a time and none twice for the same news. */
|
||||
private val reads = Reads()
|
||||
|
||||
/** The reply the person asked for from this screen last, by its id: the one that goes on behind a lock. */
|
||||
private var ownReply: String? = null
|
||||
|
||||
/** Whether the person is at the transcript's end, as the screen last said. */
|
||||
private var atEnd = true
|
||||
|
||||
override fun reading(atEnd: Boolean) {
|
||||
this.atEnd = atEnd
|
||||
}
|
||||
|
||||
/** How a reply's stream ended. */
|
||||
private sealed interface Through {
|
||||
/** With `done`; [next] is the reply the queue started after it. */
|
||||
data class Done(val next: String?) : Through
|
||||
|
||||
/** Without a `done`: the row is gone on the server, or it ended some way the stream did not tell. */
|
||||
data object Closed : Through
|
||||
|
||||
/** With an error, which has been said. */
|
||||
data object Failed : Through
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow a reply to its end, then whatever the queue started after it.
|
||||
*
|
||||
* [own]: the person asked for this reply from this screen (a message sent, an edit, Regenerate,
|
||||
* Continue). Its stream is the request they started, and goes on when the phone locks or the
|
||||
* app leaves the front, as any request under way does. Every other reply -- one the events
|
||||
* route said, one found being written when the chat was opened or read again, the queue's
|
||||
* next -- is followed only while the app is in front of an unlocked phone ([whileOpen]): when
|
||||
* that ends its stream is let go, and on the return one read catches up and follows what is
|
||||
* being written then. Without that an agent's chat with wakes queued would chain a read and a
|
||||
* stream for hours behind the lock.
|
||||
*
|
||||
* Whatever follows a stream is a new request and waits at the gate, the person's own reply's
|
||||
* too: a broken connection opened again, the read after `done` with a `next`, the read after
|
||||
* a stream that closed without `done`.
|
||||
*/
|
||||
private fun follow(messageId: String, own: Boolean) {
|
||||
val chat = _state.value.chat ?: return
|
||||
if (own) ownReply = messageId
|
||||
// Already followed, and still being written: the events route says this app's own replies
|
||||
// too, and a second stream for one reply would start its drawing over.
|
||||
if (following?.isActive == true && _state.value.live?.let { it.messageId == messageId && it.finished == null } == true) return
|
||||
following?.cancel()
|
||||
following = viewModelScope.launch {
|
||||
_state.update { it.copy(live = LiveReply(messageId)) }
|
||||
try {
|
||||
StreamClient(api()).follow(chat.id, messageId).collect { frame ->
|
||||
_state.update { s ->
|
||||
val live = (s.live ?: LiveReply(messageId)).apply(frame.event, frame.data)
|
||||
// The tree outlives the reply: kept for the activity sheet once it ends.
|
||||
s.copy(live = live, tree = live.tree ?: s.tree)
|
||||
}
|
||||
when (val through = gate.whileOpen(stays = { ownReply == messageId }) { stream(chat, messageId) }) {
|
||||
// Let go at the gate. What the stream had shown stays in the row; once the app
|
||||
// is in front again the chat is read, and what is being written then followed.
|
||||
// A stream let go after its `done` (it was open for the chat's name) left nothing unread.
|
||||
null -> {
|
||||
val mark = reads.mark()
|
||||
val unfinished = _state.value.live?.messageId == messageId
|
||||
_state.update { it.closedUnfinished(messageId, null) }
|
||||
if (unfinished) rereadAndFollow(rounds = 1, mark = mark)
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
|
||||
// The queue handed a waiting prompt to a fresh reply: the transcript has moved
|
||||
// on the server, so it is read again rather than patched, and what the read says
|
||||
// is being written is followed (the stream's word for it, where the read failed).
|
||||
is Through.Done -> through.next?.let { next ->
|
||||
gate.passLater()
|
||||
val read = refresh()
|
||||
(if (read != null) read.live else next)?.let { follow(it, own = false) }
|
||||
}
|
||||
|
||||
// The transcript is read again, so what was written is still there; where it
|
||||
// cannot be read, what the stream had shown stays.
|
||||
Through.Closed -> {
|
||||
gate.passLater()
|
||||
val reread = try {
|
||||
api().chat(chat.id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
_state.update { it.closedUnfinished(messageId, reread).capped(atEnd) }
|
||||
// Another reply is being written there (a queued turn): that one is followed.
|
||||
reread?.live?.takeIf { it != messageId }?.let { follow(it, own = false) }
|
||||
}
|
||||
|
||||
// The reply goes on on the server; what it has written so far is read back
|
||||
// rather than left half-drawn.
|
||||
_state.update { it.copy(live = null) }
|
||||
refresh()
|
||||
return@launch
|
||||
}
|
||||
val ended = _state.value.live
|
||||
_state.update { s ->
|
||||
val finished = ended?.finished
|
||||
s.copy(
|
||||
live = null,
|
||||
messages = if (finished != null) s.messages.map { if (it.id == finished.id) finished else it } else s.messages,
|
||||
chat = s.chat?.let { c -> ended?.title?.let { c.copy(title = it) } ?: c },
|
||||
)
|
||||
}
|
||||
// The queue handed a waiting prompt to a fresh reply: the transcript has moved on
|
||||
// the server, so it is read again rather than patched.
|
||||
ended?.next?.let { next ->
|
||||
refresh()
|
||||
follow(next)
|
||||
Through.Failed -> {
|
||||
gate.passLater()
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun refresh() {
|
||||
val chat = _state.value.chat ?: return
|
||||
runCatching { api().chat(chat.id) }.onSuccess { d ->
|
||||
_state.update { it.copy(chat = d.chat, messages = d.messages, more = d.more) }
|
||||
/** The stream of the reply [messageId], drawn as it comes, to its end; a connection that breaks is opened again at the gate. */
|
||||
private suspend fun stream(chat: Chat, messageId: String): Through {
|
||||
// Set at `done`, which is the end of the reply: from then on the stream is followed
|
||||
// only for the name a model may still give the chat (the `title` frame).
|
||||
var ended: LiveReply? = null
|
||||
var next: String? = null
|
||||
try {
|
||||
StreamClient(api()).follow(chat.id, messageId, turn = { gate.passLater() }).takeWhile { frame ->
|
||||
val before = ended
|
||||
if (before != null) {
|
||||
val named = before.apply(frame.event, frame.data)
|
||||
ended = named
|
||||
if (named.title != before.title) _state.update { s -> s.copy(chat = s.chat?.let { c -> named.title?.let { c.copy(title = it) } ?: c }) }
|
||||
return@takeWhile true
|
||||
}
|
||||
val live = (_state.value.live ?: LiveReply(messageId)).apply(frame.event, frame.data)
|
||||
val finished = live.finished
|
||||
if (finished == null) {
|
||||
// The tree outlives the reply: kept for the activity sheet once it ends.
|
||||
_state.update { s -> s.copy(live = live, tree = live.tree ?: s.tree) }
|
||||
return@takeWhile true
|
||||
}
|
||||
ended = live
|
||||
_state.update { s ->
|
||||
s.copy(
|
||||
live = null,
|
||||
tree = live.tree ?: s.tree,
|
||||
messages = s.messages.map { if (it.id == finished.id) finished else it },
|
||||
chat = s.chat?.let { c -> live.title?.let { c.copy(title = it) } ?: c },
|
||||
)
|
||||
}
|
||||
// With a `next` the queue's reply is followed instead of this stream's tail.
|
||||
next = live.next
|
||||
live.next == null
|
||||
}.collect { }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// After `done` only the name was still to come: nothing to say, nothing to redo.
|
||||
if (ended != null) return Through.Done(next)
|
||||
fail(e)
|
||||
_state.update { it.copy(live = null) }
|
||||
return Through.Failed
|
||||
}
|
||||
return if (ended != null) Through.Done(next) else Through.Closed
|
||||
}
|
||||
|
||||
/**
|
||||
* The transcript as the server has it now, or null where it could not be read. The older
|
||||
* pages the person loaded stay ([withNewest]); [whole] is for a change that rewrote the
|
||||
* transcript itself (a compaction), after which only what was read is true.
|
||||
*/
|
||||
private suspend fun refresh(whole: Boolean = false): ChatDetail? {
|
||||
val chat = _state.value.chat ?: return null
|
||||
val read = try {
|
||||
api().chat(chat.id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
return null
|
||||
}
|
||||
_state.update { if (whole) it.copy(chat = read.chat, messages = read.messages, more = read.more) else it.withNewest(read).capped(atEnd) }
|
||||
return read
|
||||
}
|
||||
|
||||
private fun took(turn: Turn) {
|
||||
_state.update { s ->
|
||||
s.copy(messages = s.messages.filterNot { m -> m.id == turn.message?.id || m.id == turn.reply?.id } + listOfNotNull(turn.message, turn.reply))
|
||||
s.copy(
|
||||
messages = s.messages.filterNot { m -> m.id == turn.message?.id || m.id == turn.reply?.id } + listOfNotNull(turn.message, turn.reply),
|
||||
lastSent = turn.message?.id ?: s.lastSent,
|
||||
)
|
||||
}
|
||||
turn.reply?.let { follow(it.id) }
|
||||
turn.reply?.let { follow(it.id, own = true) }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -369,8 +697,8 @@ class ChatViewModel(app: Application) :
|
||||
agents = agents,
|
||||
forceTool = if (picture) IMAGE_TOOL else null,
|
||||
)
|
||||
_state.update { it.copy(chat = made.chat, messages = listOfNotNull(made.message, made.reply)) }
|
||||
made.reply?.let { follow(it.id) }
|
||||
_state.update { it.copy(chat = made.chat, messages = listOfNotNull(made.message, made.reply), lastSent = made.message?.id) }
|
||||
made.reply?.let { follow(it.id, own = true) }
|
||||
} else {
|
||||
took(client.sendMessage(chat.id, text, files, forceTool = if (picture) IMAGE_TOOL else null))
|
||||
}
|
||||
@@ -391,14 +719,42 @@ class ChatViewModel(app: Application) :
|
||||
override fun regenerate(message: Message) = control { api, chat ->
|
||||
val turn = api.regenerate(chat.id, message.id)
|
||||
_state.update { s -> s.copy(messages = s.messages.map { if (it.id == message.id) turn.reply ?: it else it }) }
|
||||
turn.reply?.let { follow(it.id) }
|
||||
turn.reply?.let { follow(it.id, own = true) }
|
||||
}
|
||||
|
||||
override fun edit(message: Message, text: String) = control { api, chat ->
|
||||
val turn = api.edit(chat.id, message.id, text)
|
||||
// Everything after the edited turn is gone on the server; read it back.
|
||||
refresh()
|
||||
turn.reply?.let { follow(it.id) }
|
||||
turn.reply?.let { follow(it.id, own = true) }
|
||||
}
|
||||
|
||||
/**
|
||||
* A waiting message's two actions. Each is one request a tap starts. The reply a send
|
||||
* starts is the person's own, followed as one they typed for; a refusal's read waits until
|
||||
* nothing is being written on this screen (a reply's own stream says everything until
|
||||
* then, and a read beside it could draw a stale row over a finished one), and at the gate.
|
||||
*/
|
||||
private val waiting = WaitingActions(
|
||||
state = _state,
|
||||
read = { refresh() },
|
||||
follow = { follow(it.reply, it.own) },
|
||||
say = ::fail,
|
||||
catchUp = {
|
||||
val mark = reads.mark()
|
||||
_state.first { !it.running }
|
||||
rereadAndFollow(rounds = 1, mark = mark)
|
||||
},
|
||||
)
|
||||
|
||||
override fun sendNow(message: Message) {
|
||||
val chat = _state.value.chat ?: return
|
||||
viewModelScope.launch { waiting.sendNow(message) { api().sendWaiting(chat.id, message.id) } }
|
||||
}
|
||||
|
||||
override fun discard(message: Message) {
|
||||
val chat = _state.value.chat ?: return
|
||||
viewModelScope.launch { waiting.discard(message) { api().discardWaiting(chat.id, message.id) } }
|
||||
}
|
||||
|
||||
override fun continueChat() = control { api, chat -> took(api.continueChat(chat.id)) }
|
||||
@@ -408,6 +764,16 @@ class ChatViewModel(app: Application) :
|
||||
refresh()
|
||||
}
|
||||
|
||||
override fun failed(e: Throwable) = _state.update { it.copy(error = getApplication<Application>().explain(e)) }
|
||||
|
||||
private val toldFallback = mutableSetOf<String>()
|
||||
|
||||
override fun mediaFellBack(kind: String, sentence: String) {
|
||||
if (!fallbackToSay(toldFallback, kind)) return
|
||||
toldFallback += kind
|
||||
_state.update { it.copy(notice = sentence) }
|
||||
}
|
||||
|
||||
override fun answer(card: Card, answer: CardAnswer) = control { api, chat ->
|
||||
try {
|
||||
api.answer(chat.id, card.id, answer)
|
||||
@@ -422,7 +788,7 @@ class ChatViewModel(app: Application) :
|
||||
|
||||
override fun change(key: String, value: String?) = control { api, chat ->
|
||||
val updated = api.updateChat(chat.id, JsonObject(mapOf(key to JsonPrimitive(value))))
|
||||
_state.update { it.copy(chat = updated) }
|
||||
_state.update { it.copy(chat = updated, picked = if (key == "model") value else it.picked) }
|
||||
// Another model may serve one request at a time, or more: whether a team is offered
|
||||
// follows it.
|
||||
if (key == "model") {
|
||||
@@ -456,7 +822,7 @@ class ChatViewModel(app: Application) :
|
||||
}
|
||||
}
|
||||
try {
|
||||
StreamClient(client).watch { client.activityEvents(chat.id) }.collect { frame ->
|
||||
StreamClient(client).watch(turn = { gate.pass() }) { client.activityEvents(chat.id) }.collect { frame ->
|
||||
if (frame.event != "activity") return@collect
|
||||
val read = runCatching { LembasJson.decodeFromString(ActivityFrame.serializer(), frame.data) }.getOrNull() ?: return@collect
|
||||
val changed = read.version != _state.value.activity?.version
|
||||
@@ -472,6 +838,216 @@ class ChatViewModel(app: Application) :
|
||||
}
|
||||
}
|
||||
|
||||
// --- Generated media's jobs -----------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Follow the chat's long generations while the screen is in front: every job of the chat once
|
||||
* (a finished one's file is drawn on its card), then the ones under way every few seconds --
|
||||
* there is no stream frame for a job. One that ends by itself wakes the chat with a reply this
|
||||
* app did not start: when a job says the chat was told, the transcript is read again and that
|
||||
* reply followed. Runs until cancelled (the screen left, or no longer in front). An instance
|
||||
* without these routes has no jobs, and nothing is asked again. Every request waits at the
|
||||
* gate; how often a finished job was asked whether the chat was told is kept for as long as
|
||||
* the chat is open ([toldWaits]), so a return to the screen does not start that count over.
|
||||
*/
|
||||
private val toldWaits = mutableMapOf<String, Int>()
|
||||
|
||||
suspend fun watchMedia() {
|
||||
val chat = _state.value.chat ?: return
|
||||
val client = runCatching { api() }.getOrNull() ?: return
|
||||
try {
|
||||
gate.pass()
|
||||
val jobs = client.mediaJobs(chat.id)
|
||||
val before = _state.value.mediaJobs
|
||||
_state.update { it.withJobs(jobs, SystemClock.elapsedRealtime()) }
|
||||
// Away and back: a job that told the chat meanwhile left a reply this screen has not read.
|
||||
if (jobs.any { woke(before[it.id]?.job, it) }) rereadAndFollow()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// An older instance, or one out of reach: the cards say what the calls said.
|
||||
}
|
||||
while (true) {
|
||||
delay(JOB_POLL_MS)
|
||||
val now = _state.value
|
||||
val telling = now.mediaJobs.values.filter { awaitsTelling(it.job) && it.at > 0 && (toldWaits[it.job.id] ?: 0) < TELL_ROUNDS }.map { it.job.id }
|
||||
var woken = false
|
||||
for (id in (now.jobsToRead() + telling).distinct()) {
|
||||
val before = _state.value.mediaJobs[id]?.job
|
||||
// Each a request of its own: none behind a lock, or with the app not in front.
|
||||
gate.pass()
|
||||
val read = try {
|
||||
client.mediaJob(id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: ApiException) {
|
||||
// Gone, or never this person's: the card says so in the instance's words and is not asked for again.
|
||||
if (e.status != 404) continue
|
||||
val ref = now.jobRefs.firstOrNull { it.id == id }
|
||||
MediaJob(id = id, kind = before?.kind ?: ref?.kind.orEmpty(), state = "expired", error = e.message.orEmpty(), told = true)
|
||||
} catch (_: Exception) {
|
||||
continue
|
||||
}
|
||||
if (awaitsTelling(read)) toldWaits[id] = (toldWaits[id] ?: 0) + 1
|
||||
_state.update { it.withJobs(listOf(read), SystemClock.elapsedRealtime()) }
|
||||
if (woke(before, read)) woken = true
|
||||
}
|
||||
if (woken) rereadAndFollow()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The chat has news (a job ended and told it, the events route said a reply, the app is back
|
||||
* in front): its transcript as the server has it now, and the reply being written there
|
||||
* followed. A job's telling is written a moment before the reply exists, so with two
|
||||
* [rounds], where none is live yet, the chat is read once more shortly after. While this
|
||||
* screen follows a reply nothing is touched: the news waits in the queue, and the stream's
|
||||
* `next` brings it.
|
||||
*
|
||||
* Each read waits at the gate, and goes through [reads]: [mark] is the moment the news was
|
||||
* learned, and a read that began after it has answered already is not made again -- a
|
||||
* burst of frames, or a return that several watchers notice, is one read. [wanted] is asked
|
||||
* once more when it is this one's turn.
|
||||
*/
|
||||
private suspend fun rereadAndFollow(rounds: Int = 2, mark: Long = reads.mark(), wanted: () -> Boolean = { true }) {
|
||||
val chat = _state.value.chat ?: return
|
||||
var since = mark
|
||||
for (round in 0 until rounds) {
|
||||
if (round > 0) {
|
||||
delay(WAKE_PAUSE_MS)
|
||||
// The later round is there to read after the pause: only a read from now on stands for it.
|
||||
since = reads.mark()
|
||||
}
|
||||
gate.passLater()
|
||||
var failed = false
|
||||
reads.since(since, wanted = { _state.value.live == null && wanted() }) {
|
||||
val read = try {
|
||||
api().chat(chat.id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
failed = true
|
||||
return@since false
|
||||
}
|
||||
if (_state.value.live == null) {
|
||||
_state.update { it.withNewest(read).capped(atEnd) }
|
||||
read.live?.let { follow(it, own = false) }
|
||||
}
|
||||
true
|
||||
}
|
||||
if (failed || _state.value.live != null) return
|
||||
}
|
||||
}
|
||||
|
||||
// --- Replies this app did not start -------------------------------------------------------
|
||||
|
||||
/** Whether this chat's screen has been in front before: the next time is a return. */
|
||||
private var watchedReplies = false
|
||||
|
||||
/** The replies the events route said and that are waiting their turn, so each is taken up once. */
|
||||
private val heard = mutableSetOf<String>()
|
||||
|
||||
/**
|
||||
* Learn of replies nobody asked for from this screen -- a subagent that finished and woke the
|
||||
* main agent, a schedule's result, a helper's wake, a turn the linked computer started --
|
||||
* while the chat is in front: the person's events route says each reply as it starts
|
||||
* (`reply`), and the one for this chat that is not followed already is read and followed as
|
||||
* any reply is. Runs until cancelled (the screen left, or no longer in front).
|
||||
*
|
||||
* On a return to the front the chat is read once: a reply that started and ended meanwhile
|
||||
* is said by nobody. The route is listened to while that read is under way, so a reply that
|
||||
* starts just then is not missed; what it says then is checked against what the read found
|
||||
* before anything is read again. Nothing is asked while the phone is locked or the app is
|
||||
* not in front (`InstanceGate`); what was heard then is taken up on the return. An instance
|
||||
* that does not send the frame changes nothing here but that one read.
|
||||
*/
|
||||
suspend fun watchReplies() {
|
||||
if (_state.value.chat == null) return
|
||||
val app = getApplication<Application>().lembas
|
||||
val back = watchedReplies
|
||||
watchedReplies = true
|
||||
val returned = reads.mark()
|
||||
val frames = runCatching { app.eventFrames() }.getOrNull()
|
||||
try {
|
||||
coroutineScope {
|
||||
if (back) launch { rereadAndFollow(rounds = 1, mark = returned) }
|
||||
frames?.collect { frame ->
|
||||
if (frame.event != "reply") return@collect
|
||||
val said = runCatching { LembasJson.decodeFromString(ReplyFrame.serializer(), frame.data) }.getOrNull() ?: return@collect
|
||||
if (!_state.value.asksFor(said) || !heard.add(said.messageId)) return@collect
|
||||
val learned = reads.mark()
|
||||
// Not in the collector: the one connection is shared, and a watcher that
|
||||
// waits holds the others' frames back.
|
||||
launch {
|
||||
try {
|
||||
takeUp(said, learned)
|
||||
} finally {
|
||||
heard -= said.messageId
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// An older instance, or the route refused: the chat is read when it is opened, as before.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A reply the events route said, for this chat -- that it started, or (`live` false) that it
|
||||
* ended. While this screen follows a reply of its own nothing is touched: what was said waits
|
||||
* in the queue behind it, and that stream's `next` brings it; once nothing is being written
|
||||
* here, and if it is still news, the transcript is read (it holds the turn the reply answers,
|
||||
* which this screen has not seen either) and the reply being written followed. News that a
|
||||
* read begun since [learned] has already brought costs nothing: the end of a reply this
|
||||
* screen followed to its `done` is no news at all ([asksFor]).
|
||||
*/
|
||||
private suspend fun takeUp(said: ReplyFrame, learned: Long) {
|
||||
gate.pass()
|
||||
_state.first { !it.running }
|
||||
if (!_state.value.asksFor(said)) return
|
||||
rereadAndFollow(rounds = 1, mark = learned) { _state.value.asksFor(said) }
|
||||
}
|
||||
|
||||
/**
|
||||
* "Open in Files" for a generated file: the instance is asked where the file is now, by its
|
||||
* id, and [open] gets that directory. One in the trash, or gone, is said; an instance that
|
||||
* cannot say where a node is opens the folder the file was written to, as before.
|
||||
*/
|
||||
fun whereIs(media: GeneratedMedia, open: (String) -> Unit) {
|
||||
viewModelScope.launch {
|
||||
val app = getApplication<Application>()
|
||||
try {
|
||||
val node = if (media.nodeId.isBlank()) null else api().fileNode(media.nodeId)
|
||||
when (val where = whereabouts(node, media.path)) {
|
||||
is Whereabouts.Folder -> open(where.path)
|
||||
Whereabouts.Trashed -> _state.update { it.copy(error = app.getString(R.string.media_in_trash)) }
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
when {
|
||||
noSuchRoute(e) -> open(media.folder)
|
||||
e is ApiException && e.status == 404 -> _state.update { it.copy(error = app.getString(R.string.media_gone)) }
|
||||
else -> fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop a generation: the job as it is after, in the card. One that has ended stays what it was. */
|
||||
fun cancelJob(job: MediaJob) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val after = api().cancelMediaJob(job.id)
|
||||
_state.update { it.withJobs(listOf(after), SystemClock.elapsedRealtime()) }
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var panelOpen = false
|
||||
|
||||
fun panel(open: Boolean) {
|
||||
@@ -516,7 +1092,7 @@ class ChatViewModel(app: Application) :
|
||||
_state.update { it.copy(compacting = true) }
|
||||
try {
|
||||
api().compact(chat.id)
|
||||
refresh()
|
||||
refresh(whole = true)
|
||||
loadActivity()
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
@@ -531,10 +1107,23 @@ class ChatViewModel(app: Application) :
|
||||
then()
|
||||
}
|
||||
|
||||
/** How many uploads and attachings are under way: `uploading` holds until the last has ended. */
|
||||
private var uploads = 0
|
||||
|
||||
private fun uploadBegins() {
|
||||
uploads++
|
||||
_state.update { it.copy(uploading = true) }
|
||||
}
|
||||
|
||||
private fun uploadEnds() {
|
||||
uploads = (uploads - 1).coerceAtLeast(0)
|
||||
_state.update { it.copy(uploading = uploads > 0) }
|
||||
}
|
||||
|
||||
override fun attach(uris: List<Uri>) {
|
||||
if (uris.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(uploading = true) }
|
||||
uploadBegins()
|
||||
try {
|
||||
val resolver = getApplication<Application>().contentResolver
|
||||
for (uri in uris) {
|
||||
@@ -553,7 +1142,57 @@ class ChatViewModel(app: Application) :
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
_state.update { it.copy(uploading = false) }
|
||||
uploadEnds()
|
||||
}
|
||||
}
|
||||
|
||||
private var suggesting: Job? = null
|
||||
|
||||
override fun suggest(query: String?) {
|
||||
suggesting?.cancel()
|
||||
if (query == null) {
|
||||
if (_state.value.mentions.isNotEmpty()) _state.update { it.copy(mentions = emptyList()) }
|
||||
return
|
||||
}
|
||||
suggesting = viewModelScope.launch {
|
||||
// Asked once the typing pauses, not at every letter.
|
||||
delay(MENTION_PAUSE_MS)
|
||||
val where = _state.value.let { Triple(it.chat?.id, it.device?.id, it.draft.directory) }
|
||||
val found = try {
|
||||
offered(query)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// An older server, or a device that cannot answer: nothing is offered.
|
||||
emptyList()
|
||||
}
|
||||
// Another computer or folder was chosen meanwhile: these were its files, not this one's.
|
||||
_state.update { if (Triple(it.chat?.id, it.device?.id, it.draft.directory) == where) it.copy(mentions = found) else it }
|
||||
}
|
||||
}
|
||||
|
||||
/** An agent chat's `@` is its device's files (the device reads them); a chat's is the server's. */
|
||||
private suspend fun offered(query: String): List<Mention> {
|
||||
val now = _state.value
|
||||
val chat = now.chat
|
||||
if (chat?.kind == "agent" || (chat == null && agentChat)) {
|
||||
val device = chat?.device?.tokenId ?: now.device?.id ?: return emptyList()
|
||||
return api().deviceFiles(device, query, chatId = chat?.id, cwd = now.draft.directory).files.mapNotNull { it.asMention() }.take(MENTION_LIMIT)
|
||||
}
|
||||
return api().mentions(query, chat?.id).items.take(MENTION_LIMIT)
|
||||
}
|
||||
|
||||
override fun mention(item: Mention) {
|
||||
_state.update { it.copy(mentions = emptyList()) }
|
||||
viewModelScope.launch {
|
||||
uploadBegins()
|
||||
try {
|
||||
val stored = api().attachFrom(item, _state.value.chat?.id)
|
||||
_state.update { it.copy(pending = it.pending + stored) }
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
uploadEnds()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -584,4 +1223,11 @@ class ChatViewModel(app: Application) :
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MENTION_PAUSE_MS = 250L
|
||||
|
||||
/** Between a job's "the chat was told" and the reply that telling starts. */
|
||||
const val WAKE_PAUSE_MS = 2000L
|
||||
}
|
||||
}
|
||||
@@ -28,12 +28,16 @@ import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.ArrowUpward
|
||||
import androidx.compose.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.Brush
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.Link
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.PhotoCamera
|
||||
import androidx.compose.material.icons.filled.PhotoLibrary
|
||||
@@ -51,7 +55,6 @@ import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.InputChip
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.RangeSlider
|
||||
import androidx.compose.material3.SliderDefaults
|
||||
import androidx.compose.material3.Surface
|
||||
@@ -83,12 +86,15 @@ import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.AgentsSetting
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.Mention
|
||||
import eu.llembas.android.assist.PhoneRecognizer
|
||||
import eu.llembas.android.assist.Recorder
|
||||
import eu.llembas.android.assist.usePhoneRecognizer
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.DirectoryPicker
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@@ -209,6 +215,9 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: ()
|
||||
}
|
||||
// A suggestion from the empty chat lands here (a new value each tap).
|
||||
LaunchedEffect(initial) { if (initial.isNotBlank()) text = initial }
|
||||
// Asked again when the words change -- and when the computer or the folder does: an
|
||||
// agent chat's `@` is that folder's files.
|
||||
LaunchedEffect(text, state.chat?.id, state.device?.id, state.draft.directory) { actions.suggest(mentionQuery(text)) }
|
||||
val newAgent = agent && state.chat == null
|
||||
val canSend = (text.isNotBlank() || state.pending.isNotEmpty()) && !state.uploading && (!newAgent || state.device != null)
|
||||
val summary = tuneSummary(state, agent)
|
||||
@@ -262,6 +271,19 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: ()
|
||||
}
|
||||
}
|
||||
}
|
||||
// What `@` offers for the word being typed, above the words: a tap attaches it (the
|
||||
// server's files, earlier attachments, pages) or completes it (a device's file).
|
||||
if (state.mentions.isNotEmpty() && mentionQuery(text) != null) {
|
||||
MentionList(state.mentions) { item ->
|
||||
if (item.kind == MENTION_DEVICE) {
|
||||
text = withMention(text, item.path)
|
||||
} else {
|
||||
text = withoutMention(text)
|
||||
actions.mention(item)
|
||||
}
|
||||
actions.suggest(null)
|
||||
}
|
||||
}
|
||||
TextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
@@ -374,8 +396,18 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: ()
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
if (wav.isNotEmpty()) {
|
||||
runCatching { context.lembas.instances.client()?.transcribe(wav) }
|
||||
.onSuccess { heard -> if (!heard.isNullOrBlank()) text = (text + " " + heard).trim() }
|
||||
// A transcription that was refused or never arrived is said: a field
|
||||
// that stays as it was, without a word, reads as "nothing was heard".
|
||||
try {
|
||||
val heard = context.lembas.instances.client()?.transcribe(wav, media = state.mediaFor)
|
||||
val said = heard?.text
|
||||
if (!said.isNullOrBlank()) text = (text + " " + said).trim()
|
||||
heard?.fallback?.let { actions.mediaFellBack(MEDIA_DICTATION, context.getString(R.string.transcribed_by_fallback, it)) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
actions.failed(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
|
||||
@@ -419,6 +451,48 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: ()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The `@` list: at most a few rows in view, the rest scrolled to. A row is 48 dp; its name
|
||||
* gives, and where it is (a path, a kind) is one quiet line under it.
|
||||
*/
|
||||
@Composable
|
||||
private fun MentionList(items: List<Mention>, onPick: (Mention) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth().heightIn(max = 216.dp).verticalScroll(rememberScrollState()).padding(top = 8.dp)) {
|
||||
items.take(MENTION_LIMIT).forEach { item ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { onPick(item) }.heightIn(min = 48.dp).padding(horizontal = 16.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
when (item.kind) {
|
||||
"url" -> Icons.Filled.Link
|
||||
"attachment" -> Icons.Filled.AttachFile
|
||||
else -> if (item.detail.endsWith("/")) Icons.Filled.Folder else Icons.Filled.Description
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = palette.inkMuted,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
item.name.ifBlank {
|
||||
item.path.ifBlank { item.url }
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (item.detail.isNotBlank() && item.detail != item.name) {
|
||||
Text(item.detail, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- The tune sheet --------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
@@ -549,26 +623,15 @@ fun TuneContent(state: ChatState, actions: ChatActions, agent: Boolean, modifier
|
||||
}
|
||||
|
||||
if (askDirectory) {
|
||||
var typed by remember { mutableStateOf(state.draft.directory) }
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { askDirectory = false },
|
||||
title = { Text(stringResource(R.string.agent_directory)) },
|
||||
text = {
|
||||
OutlinedTextField(
|
||||
value = typed,
|
||||
onValueChange = { typed = it },
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.agent_directory_hint)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
DirectoryPicker(
|
||||
title = stringResource(R.string.agent_directory),
|
||||
initial = state.draft.directory,
|
||||
load = actions::directories,
|
||||
onPick = { path ->
|
||||
actions.updateDraft { it.copy(directory = path) }
|
||||
askDirectory = false
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(onClick = {
|
||||
actions.updateDraft { it.copy(directory = typed.trim()) }
|
||||
askDirectory = false
|
||||
}) { Text(stringResource(R.string.save)) }
|
||||
},
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = { askDirectory = false }) { Text(stringResource(R.string.cancel)) } },
|
||||
onDismiss = { askDirectory = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.DiffLine
|
||||
import eu.llembas.android.api.DiffSign
|
||||
import eu.llembas.android.api.DiffView
|
||||
import eu.llembas.android.api.FileDiff
|
||||
import eu.llembas.android.api.view
|
||||
import eu.llembas.android.api.visibly
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.theme.Palette
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
// An edit's diff on its approval card: per file its path, how many lines come and go, and the
|
||||
// changed lines as text -- a sign before each and the theme's colour behind it, in one width of
|
||||
// letter. The lines scroll sideways in a box of their own, so the card never does. Both texts
|
||||
// are a model's and a file's words: one plain Text draws them, and nothing in them is rendered.
|
||||
|
||||
/** The most of one line that is drawn: a line of a megabyte is still one line of the card. */
|
||||
internal const val DIFF_LINE_MOST = 400
|
||||
|
||||
private val DiffShape = RoundedCornerShape(12.dp)
|
||||
|
||||
/**
|
||||
* A line as the card writes it: its sign, then its text cut at [DIFF_LINE_MOST], with whatever
|
||||
* a person could not see in it -- a direction override, a zero-width space, a line separator --
|
||||
* written as its code point ([visibly]).
|
||||
*/
|
||||
internal fun diffRow(line: DiffLine): String {
|
||||
val sign = when (line.sign) {
|
||||
DiffSign.Added -> "+ "
|
||||
DiffSign.Removed -> "- "
|
||||
DiffSign.Same -> " "
|
||||
DiffSign.Gap -> return "⋯"
|
||||
}
|
||||
val long = line.text.length > DIFF_LINE_MOST
|
||||
return sign + visibly(if (long) line.text.take(DIFF_LINE_MOST) else line.text) + if (long) "…" else ""
|
||||
}
|
||||
|
||||
private fun diffText(lines: List<DiffLine>, palette: Palette): AnnotatedString = buildAnnotatedString {
|
||||
lines.forEachIndexed { at, line ->
|
||||
val style = when (line.sign) {
|
||||
DiffSign.Added -> SpanStyle(color = palette.success, background = palette.successSoft)
|
||||
DiffSign.Removed -> SpanStyle(color = palette.danger, background = palette.dangerSoft)
|
||||
DiffSign.Same -> SpanStyle(color = palette.ink)
|
||||
DiffSign.Gap -> SpanStyle(color = palette.inkFaint)
|
||||
}
|
||||
withStyle(style) { append(diffRow(line)) }
|
||||
if (at < lines.lastIndex) append('\n')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The diffs of an item, worked out: null until they are. Off the main thread -- two texts of a
|
||||
* megabyte are not compared inside a frame -- and one file after another, so fifty files hold
|
||||
* one comparison's memory at a time. A screenshot has no later frame: there it is done at once.
|
||||
*/
|
||||
@Composable
|
||||
fun diffViews(diffs: List<FileDiff>): List<DiffView>? {
|
||||
if (diffs.isEmpty()) return emptyList()
|
||||
if (LocalInspectionMode.current) return remember(diffs) { diffs.map { it.view() } }
|
||||
val views by produceState<List<DiffView>?>(null, diffs) {
|
||||
value = withContext(Dispatchers.Default) {
|
||||
diffs.map {
|
||||
ensureActive()
|
||||
it.view()
|
||||
}
|
||||
}
|
||||
}
|
||||
return views
|
||||
}
|
||||
|
||||
/** The diffs of one item of an approval card, a block per file; [views] as [diffViews] gave them. */
|
||||
@Composable
|
||||
fun CardDiffs(diffs: List<FileDiff>, views: List<DiffView>?, modifier: Modifier = Modifier) {
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
diffs.forEachIndexed { at, diff -> key(at, diff.path) { FileDiffBlock(diff, views?.getOrNull(at)) } }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One file's change. The path gives (it wraps) and the two counts keep their width. The lines
|
||||
* are folded to the first few; "Show all" opens them, up to what a card lays out. Until [view]
|
||||
* is worked out the block is its path alone.
|
||||
*/
|
||||
@Composable
|
||||
private fun FileDiffBlock(diff: FileDiff, view: DiffView?) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(diff.path) { mutableStateOf(false) }
|
||||
val path = remember(diff.path) { visibly(diff.path) }
|
||||
Column(Modifier.fillMaxWidth().clip(DiffShape).background(palette.codeBg).border(1.dp, palette.codeBorder, DiffShape)) {
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(path, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace, color = palette.ink)
|
||||
val state = when {
|
||||
diff.deleted -> stringResource(R.string.diff_deleted)
|
||||
diff.made -> stringResource(R.string.files_new_file)
|
||||
else -> null
|
||||
}
|
||||
if (state != null) Text(state, style = MaterialTheme.typography.labelSmall, color = palette.inkMuted)
|
||||
}
|
||||
if (view != null) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
val counts = stringResource(R.string.diff_counts, view.added.toString(), view.removed.toString())
|
||||
Row(Modifier.clearAndSetSemantics { contentDescription = counts }, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("+${view.added}", style = MaterialTheme.typography.labelMedium, fontFamily = FontFamily.Monospace, color = palette.success)
|
||||
Text("−${view.removed}", style = MaterialTheme.typography.labelMedium, fontFamily = FontFamily.Monospace, color = palette.danger)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (view != null) {
|
||||
// Said once, where every line would otherwise go and come with the same words.
|
||||
view.endings?.let { (from, to) -> DiffNote(stringResource(R.string.diff_endings, from, to)) }
|
||||
val lines = view.shown(open)
|
||||
if (lines.isNotEmpty()) {
|
||||
val text = remember(lines, palette) { diffText(lines, palette) }
|
||||
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
softWrap = false,
|
||||
modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (open && view.beyond > 0) DiffNote(stringResource(R.string.diff_more, view.beyond.toString()))
|
||||
if (view.cut) DiffNote(stringResource(R.string.diff_cut))
|
||||
if (view.folds) {
|
||||
TextButton(onClick = { open = !open }, modifier = Modifier.heightIn(min = 48.dp).padding(horizontal = 4.dp)) {
|
||||
Text(if (open) stringResource(R.string.diff_show_less) else stringResource(R.string.diff_show_all, view.lines.size.toString()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A sentence of the block's own, under its lines. */
|
||||
@Composable
|
||||
private fun DiffNote(text: String) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = LocalPalette.current.inkMuted,
|
||||
modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import eu.llembas.android.api.Message
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
|
||||
/*
|
||||
* Whether a list keeps to its end while something is written into it. The rule, the same for the
|
||||
* chat's transcript and the assistant's sheet: the view follows only while the person is at the
|
||||
* end; once they have scrolled away it stays exactly where they are, and coming back to the end
|
||||
* takes the following up again. Nothing here knows Compose, so the tests read it as it is.
|
||||
*/
|
||||
|
||||
/** What happened to the transcript's rows between two draws. */
|
||||
enum class TranscriptChange {
|
||||
/** Nothing to follow: no rows, or the same rows. */
|
||||
None,
|
||||
|
||||
/** A chat shown for the first time, or another chat in the same place. */
|
||||
Opened,
|
||||
|
||||
/** A message this app just sent is new at the end: sending always shows what was sent. */
|
||||
Sent,
|
||||
|
||||
/** New rows at the end that the person did not write: a reply, the queue's next turn. */
|
||||
Appended,
|
||||
|
||||
/** An older page was put in front; the end has not moved. */
|
||||
Older,
|
||||
|
||||
/** Rows changed in place: a finished reply for the one being written, a transcript read again. */
|
||||
Changed,
|
||||
}
|
||||
|
||||
/**
|
||||
* What changed from [before] to [after]. [before] is null when this draw is the first one this
|
||||
* list makes; [restored] then says the list had rows before (a rotation, a return to the
|
||||
* screen), so its place is the one it kept, not a chat being opened. [sent] is the id of the
|
||||
* message this app sent last: only that one is "sent". The person's row arriving from
|
||||
* elsewhere -- written on the page or another device while this chat is open here -- is a row
|
||||
* like a reply's, and does not pull a reader down.
|
||||
*/
|
||||
fun transcriptChange(before: List<Message>?, after: List<Message>, restored: Boolean = false, sent: String? = null): TranscriptChange {
|
||||
if (after.isEmpty()) return TranscriptChange.None
|
||||
if (before == null) return if (restored) TranscriptChange.Changed else TranscriptChange.Opened
|
||||
val known = before.mapTo(HashSet()) { it.id }
|
||||
val firstKept = after.indexOfFirst { it.id in known }
|
||||
if (firstKept < 0) return TranscriptChange.Opened
|
||||
val added = after.subList(after.indexOfLast { it.id in known } + 1, after.size)
|
||||
return when {
|
||||
sent != null && added.any { it.id == sent } -> TranscriptChange.Sent
|
||||
added.isNotEmpty() -> TranscriptChange.Appended
|
||||
firstKept > 0 -> TranscriptChange.Older
|
||||
before == after -> TranscriptChange.None
|
||||
else -> TranscriptChange.Changed
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the view goes to the end after [change], given whether it was [following]. Opening a
|
||||
* chat and sending a message always do; an older page never does; everything else -- and a reply
|
||||
* growing, a keyboard opening -- only for a person who is at the end already, and never while
|
||||
* the list is being scrolled by the person ([personScrolling]): a wheel, a key or a screen
|
||||
* reader moving it upwards has not come to rest yet, so the following has not ended yet, and
|
||||
* going to the end now would cancel that scroll and throw the reader back down.
|
||||
*/
|
||||
fun movesToEnd(change: TranscriptChange, following: Boolean, personScrolling: Boolean = false): Boolean = when (change) {
|
||||
TranscriptChange.Opened, TranscriptChange.Sent -> true
|
||||
TranscriptChange.None, TranscriptChange.Older -> false
|
||||
TranscriptChange.Appended, TranscriptChange.Changed -> following && !personScrolling
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a scroll is the person's. One that is [inProgress] and that this app did not start
|
||||
* ([ownScrolls]: how many of the app's own scrolls are under way) is theirs, whatever moved
|
||||
* the list -- a finger, a wheel, a keyboard, a screen reader. The app marks its own; everything
|
||||
* else is somebody.
|
||||
*/
|
||||
fun personScrolls(inProgress: Boolean, ownScrolls: Int): Boolean = inProgress && ownScrolls <= 0
|
||||
|
||||
/**
|
||||
* Whether a scroll that has come to rest was the person's: a finger was on the list
|
||||
* ([touched]), the list went back towards its start ([wentBack]), or the scroll began with
|
||||
* none of this app's own under way ([startedByApp] false).
|
||||
*/
|
||||
fun scrollWasPersons(touched: Boolean, wentBack: Boolean, startedByApp: Boolean): Boolean = touched || wentBack || !startedByApp
|
||||
|
||||
/**
|
||||
* Whether the view follows, once a scroll has come to rest [distance] pixels short of the end.
|
||||
* Within [slack] counts as the end: a line that arrived while the list was settling must not
|
||||
* read as "scrolled away".
|
||||
*/
|
||||
fun followsAt(distance: Int, slack: Int): Boolean = distance <= slack
|
||||
|
||||
/**
|
||||
* Whether the view follows once a scroll has come to rest. Only a scroll the person made
|
||||
* ([byPerson]: a finger on the list, or the list gone back towards its start, which this
|
||||
* app's own scroll to the end never does) can end the following, by where it rests. Any other scroll is this
|
||||
* app's own keeping to the end; a line, a card or a picture that arrived before it settled
|
||||
* leaves it short of the end without anybody having left, and reading that as "scrolled away"
|
||||
* is what switches the following off under a person who never moved. Such a scroll can only
|
||||
* take the following up (it rested at the end), never end it.
|
||||
*/
|
||||
fun restFollows(following: Boolean, byPerson: Boolean, distance: Int, slack: Int): Boolean = if (byPerson) {
|
||||
followsAt(distance, slack)
|
||||
} else {
|
||||
following ||
|
||||
followsAt(distance, slack)
|
||||
}
|
||||
|
||||
/** Whether a list that stood at row [fromIndex], [fromOffset] pixels into it, has gone back towards its start. */
|
||||
fun wentBack(fromIndex: Int, fromOffset: Int, toIndex: Int, toOffset: Int): Boolean = toIndex < fromIndex || (toIndex == fromIndex && toOffset < fromOffset)
|
||||
|
||||
/**
|
||||
* The row that keeps its place when an older page arrives while the list stands at its very
|
||||
* top: the first row there was before, by its place in [after]. Null when it is gone.
|
||||
*/
|
||||
fun keptRow(before: List<Message>, after: List<Message>): Int? {
|
||||
val first = before.firstOrNull() ?: return null
|
||||
return after.indexOfFirst { it.id == first.id }.takeIf { it >= 0 }
|
||||
}
|
||||
|
||||
/**
|
||||
* A scroll this app makes for the person ([scroll]: to the end, as the reply grows). A finger
|
||||
* on the list takes it over, and Compose ends the scroll by cancelling it -- which, left
|
||||
* alone, would also end whatever follower called it, for good. So that cancellation is taken
|
||||
* here, and only that one: when the follower itself is cancelled, it still ends.
|
||||
*/
|
||||
suspend fun yielding(scroll: suspend () -> Unit) {
|
||||
try {
|
||||
scroll()
|
||||
} catch (e: CancellationException) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [yielding], counted in [own] while it runs: how the list's watchers tell this app's scroll
|
||||
* from the person's ([personScrolls]). A count and not a flag: one of the app's scrolls may
|
||||
* overtake another, and the first one's end must not unmark the second.
|
||||
*/
|
||||
suspend fun ownScroll(own: IntArray, scroll: suspend () -> Unit) {
|
||||
own[0]++
|
||||
try {
|
||||
yielding(scroll)
|
||||
} finally {
|
||||
own[0]--
|
||||
}
|
||||
}
|
||||
@@ -11,12 +11,15 @@ import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -36,34 +39,54 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.GeneratedImage
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
/**
|
||||
* The pictures the instance made, fetched the one way the app fetches a chat's files: by
|
||||
* attachment id, from the instance it is signed in to, with its token. There is no URL to
|
||||
* follow -- a model's words can name an address, but never a picture this draws -- and nothing
|
||||
* bigger than [MAX_BYTES] is decoded.
|
||||
* The pictures the instance made, fetched the two ways the app fetches a chat's files: by
|
||||
* attachment id, or -- for a generated file with no attachment -- by its node id in the
|
||||
* person's Files; always from the instance it is signed in to, with its token. There is no URL
|
||||
* to follow -- a model's words can name an address, but never a picture this draws -- and
|
||||
* nothing bigger than [MAX_BYTES] is decoded.
|
||||
*/
|
||||
private object Pictures {
|
||||
/** Longest edge decoded: enough for a phone held either way, small enough to keep a few. */
|
||||
private const val EDGE = 1600
|
||||
private const val MAX_BYTES = 24 * 1024 * 1024
|
||||
const val MAX_BYTES = 24L * 1024 * 1024
|
||||
private val cache = LruCache<String, ImageBitmap>(8)
|
||||
private val failed = mutableSetOf<String>()
|
||||
private val gone = mutableSetOf<String>()
|
||||
|
||||
fun cached(id: String): ImageBitmap? = cache.get(id)
|
||||
fun cached(key: String): ImageBitmap? = cache.get(key)
|
||||
|
||||
suspend fun load(context: Context, id: String): ImageBitmap? {
|
||||
cache.get(id)?.let { return it }
|
||||
if (id.isBlank() || id in failed) return null
|
||||
/** Whether the instance said there is no such file (any more). */
|
||||
fun isGone(key: String): Boolean = key in gone
|
||||
|
||||
suspend fun load(context: Context, key: String, fetch: suspend (ApiClient) -> ByteArray): ImageBitmap? {
|
||||
cache.get(key)?.let { return it }
|
||||
if (key in failed) return null
|
||||
val api = context.lembas.instances.client() ?: return null
|
||||
val bytes = runCatching { api.attachmentBytes(id) }.getOrNull()?.takeIf { it.size <= MAX_BYTES }
|
||||
// A picture that comes into view behind the lock, or with the app not in front, waits there.
|
||||
context.lembas.gate.passLater()
|
||||
val bytes = try {
|
||||
fetch(api).takeIf { it.size <= MAX_BYTES }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
if (e is ApiException && e.status == 404) gone += key
|
||||
null
|
||||
}
|
||||
val image = bytes?.let { decode(it) }
|
||||
if (image == null) failed += id else cache.put(id, image)
|
||||
if (image == null) failed += key else cache.put(key, image)
|
||||
return image
|
||||
}
|
||||
|
||||
@@ -84,20 +107,57 @@ private object Pictures {
|
||||
*/
|
||||
@Composable
|
||||
fun GeneratedPicture(image: GeneratedImage, modifier: Modifier = Modifier) {
|
||||
if (image.id.isBlank()) return
|
||||
Picture("attachment:" + image.id, image.width, image.height, modifier) { api -> api.attachmentBytes(image.id) }
|
||||
}
|
||||
|
||||
/**
|
||||
* A generated picture that is a file of the person's Files and no attachment: fetched by its
|
||||
* node id from `/files/raw`, drawn the same way. One the person has since put in the trash
|
||||
* says that it is no longer there.
|
||||
*/
|
||||
@Composable
|
||||
fun GeneratedPicture(media: GeneratedMedia, modifier: Modifier = Modifier) {
|
||||
if (media.nodeId.isBlank()) return
|
||||
Picture("node:" + media.nodeId, media.width, media.height, modifier) { api ->
|
||||
// What the server says it weighs decides before a byte is asked for.
|
||||
if (media.size > Pictures.MAX_BYTES) throw ApiException(413, "")
|
||||
val held = ByteArrayOutputStream()
|
||||
api.download(api.raw(Raw.Node(media.nodeId), inline = true), held, most = Pictures.MAX_BYTES)
|
||||
held.toByteArray()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape a picture's place is given before its bytes are there: width over height, from the
|
||||
* size the server said, kept between a quarter and four. A size the server did not say is a
|
||||
* square. The place is that shape from its first draw to its last, so the picture arriving (or
|
||||
* not arriving) moves nothing in the transcript.
|
||||
*/
|
||||
internal fun pictureRatio(width: Int, height: Int): Float = if (width > 0 && height > 0) (width.toFloat() / height).coerceIn(0.25f, 4f) else 1f
|
||||
|
||||
@Composable
|
||||
private fun Picture(key: String, width: Int, height: Int, modifier: Modifier, fetch: suspend (ApiClient) -> ByteArray) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val still = LocalInspectionMode.current
|
||||
var bitmap by remember(image.id) { mutableStateOf(Pictures.cached(image.id)) }
|
||||
var bitmap by remember(key) { mutableStateOf(Pictures.cached(key)) }
|
||||
var gone by remember(key) { mutableStateOf(Pictures.isGone(key)) }
|
||||
var whole by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(image.id) { if (bitmap == null && !still) bitmap = Pictures.load(context, image.id) }
|
||||
val ratio = if (image.width > 0 && image.height > 0) image.width.toFloat() / image.height else 1f
|
||||
LaunchedEffect(key) {
|
||||
if (bitmap == null && !still) {
|
||||
bitmap = Pictures.load(context, key, fetch)
|
||||
gone = Pictures.isGone(key)
|
||||
}
|
||||
}
|
||||
val ratio = pictureRatio(width, height)
|
||||
val shape = RoundedCornerShape(16.dp)
|
||||
val described = stringResource(R.string.image_generated)
|
||||
Box(
|
||||
modifier
|
||||
.widthIn(max = 480.dp)
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(ratio.coerceIn(0.25f, 4f))
|
||||
.aspectRatio(ratio)
|
||||
.clip(shape)
|
||||
.background(palette.surfaceRaised)
|
||||
.border(1.dp, palette.border, shape)
|
||||
@@ -107,6 +167,8 @@ fun GeneratedPicture(image: GeneratedImage, modifier: Modifier = Modifier) {
|
||||
val shown = bitmap
|
||||
if (shown != null) {
|
||||
Image(shown, contentDescription = described, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
} else if (gone) {
|
||||
Text(stringResource(R.string.media_gone), color = palette.inkMuted, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(16.dp))
|
||||
} else {
|
||||
Icon(Icons.Filled.Image, contentDescription = described, tint = palette.inkFaint, modifier = Modifier.size(32.dp))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.os.SystemClock
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.FolderOpen
|
||||
import androidx.compose.material.icons.filled.FolderZip
|
||||
import androidx.compose.material.icons.filled.HourglassEmpty
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.Movie
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material.icons.filled.PictureAsPdf
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.ViewInAr
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.FilledIconButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.GeneratedImage
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaView
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.playTime
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
// What a model made or an agent showed, in the reply: a card for a file (a picture drawn, a video
|
||||
// or a track with Play, a PDF with Open, a 3D model or anything else as what it is) and a card for
|
||||
// a generation still under way.
|
||||
// The file is one of the person's Files, so each card leads there, and out of the app the ways
|
||||
// a file leaves it: saved where the person chooses, shared, or opened with another app. The
|
||||
// cards are drawn only where a chat provides [LocalChatMedia] -- the chat's own screen, which
|
||||
// is never over the lock screen; the assistant's sheet provides none and draws none.
|
||||
|
||||
/** What the media cards of a chat can do; nothing by default, for the screenshot tests. */
|
||||
interface MediaActions {
|
||||
/** Play a generated video or track, over the chat. */
|
||||
fun play(media: GeneratedMedia) {}
|
||||
|
||||
/** Play sound or video the person attached. */
|
||||
fun play(attachment: Attachment) {}
|
||||
|
||||
/** Lay a document's pages out over the chat (a PDF). */
|
||||
fun view(media: GeneratedMedia) {}
|
||||
|
||||
/** The folder of the person's Files the file is in. */
|
||||
fun openInFiles(media: GeneratedMedia) {}
|
||||
|
||||
/** Save it where the person chooses (the system's "Save to" page). */
|
||||
fun download(media: GeneratedMedia) {}
|
||||
|
||||
fun share(media: GeneratedMedia) {}
|
||||
|
||||
fun openWith(media: GeneratedMedia) {}
|
||||
|
||||
/** Stop a generation that is under way. */
|
||||
fun cancel(job: MediaJob) {}
|
||||
}
|
||||
|
||||
/** A chat's generated media as its cards need it: what is known of its jobs, and what a card can do. */
|
||||
class ChatMedia(val jobs: Map<String, JobSeen>, val actions: MediaActions)
|
||||
|
||||
/** Provided by the chat's screen; null anywhere else, and then no media card is drawn. */
|
||||
val LocalChatMedia = compositionLocalOf<ChatMedia?> { null }
|
||||
|
||||
private val CardShape = RoundedCornerShape(16.dp)
|
||||
|
||||
/** The string for a kind this app has a word for; null for any other. */
|
||||
internal fun mediaKindWord(kind: String): Int? = when (kind) {
|
||||
"image", "image_edit" -> R.string.media_image
|
||||
"video" -> R.string.media_video
|
||||
"music" -> R.string.media_music
|
||||
"audio" -> R.string.media_audio
|
||||
"model3d" -> R.string.media_model
|
||||
"pdf" -> R.string.media_pdf
|
||||
"archive" -> R.string.media_archive
|
||||
"text" -> R.string.media_text
|
||||
"binary" -> R.string.media_binary
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* The word for what a file is: a picture, a video, music, audio, a 3D model, a PDF, an archive,
|
||||
* a text file, a file. A kind this app does not know is the server's own word for a generated
|
||||
* file and "File" for one an agent showed ([shown]): a shown file always says what it is.
|
||||
*/
|
||||
@Composable
|
||||
internal fun mediaKind(kind: String, shown: Boolean = false): String =
|
||||
mediaKindWord(kind)?.let { stringResource(it) } ?: if (shown) stringResource(R.string.media_binary) else kind
|
||||
|
||||
/** The mark of a kind; `binary` and a kind this app does not know are a file. */
|
||||
internal fun mediaIcon(kind: String): ImageVector = when (kind) {
|
||||
"image", "image_edit" -> Icons.Filled.Image
|
||||
"video" -> Icons.Filled.Movie
|
||||
"music", "audio" -> Icons.Filled.MusicNote
|
||||
"model3d" -> Icons.Filled.ViewInAr
|
||||
"pdf" -> Icons.Filled.PictureAsPdf
|
||||
"archive" -> Icons.Filled.FolderZip
|
||||
"text" -> Icons.Filled.Description
|
||||
else -> Icons.AutoMirrored.Filled.InsertDriveFile
|
||||
}
|
||||
|
||||
/** What is known of a file, in one line: what it is, how long, how large, its size in pixels. */
|
||||
@Composable
|
||||
internal fun mediaFacts(media: GeneratedMedia): String {
|
||||
val context = LocalContext.current
|
||||
return listOfNotNull(
|
||||
mediaKind(media.kind, media.shown).ifBlank { null },
|
||||
media.seconds.takeIf { it > 0 }?.let { playTime((it * 1000).toInt()) },
|
||||
media.size.takeIf { it > 0 }?.let { Formatter.formatShortFileSize(context, it) },
|
||||
if (media.width > 0 && media.height > 0) "${media.width} × ${media.height}" else null,
|
||||
).joinToString(" · ")
|
||||
}
|
||||
|
||||
/**
|
||||
* A file a tool call made, or one an agent showed. A picture is drawn -- from its attachment
|
||||
* where the call has one ([image]), else from the file itself; a video or a track is its name
|
||||
* with Play (48 dp), which opens the player over the chat; a PDF is its name with Open, which
|
||||
* lays its pages out over the chat; a 3D model, an archive and anything this app does not know
|
||||
* is its name and what it is. Under each, four buttons of one size: Open in Files, Download,
|
||||
* Share, Open with.
|
||||
*
|
||||
* A file that was shown is always named: its picture has its name and facts under it, so one
|
||||
* that cannot be drawn on this phone (too large, a format the phone does not read) is still a
|
||||
* name, a kind in words and the ways to the file.
|
||||
*/
|
||||
@Composable
|
||||
fun MediaCard(media: GeneratedMedia, image: GeneratedImage?, actions: MediaActions, modifier: Modifier = Modifier) {
|
||||
Column(modifier.widthIn(max = 480.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
when (media.view) {
|
||||
MediaView.Picture -> {
|
||||
// A result that names no node has no picture to ask for: its row stands in, so the card is never empty.
|
||||
val drawable = (image != null && image.id.isNotBlank()) || media.nodeId.isNotBlank()
|
||||
if (image != null && image.id.isNotBlank()) GeneratedPicture(image) else GeneratedPicture(media)
|
||||
if (media.shown && drawable) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 4.dp)) { MediaWords(media) }
|
||||
} else if (!drawable) {
|
||||
MediaRow(media, actions)
|
||||
}
|
||||
}
|
||||
|
||||
MediaView.Video, MediaView.Sound, MediaView.Document, MediaView.Details -> MediaRow(media, actions)
|
||||
}
|
||||
// Four buttons of 48 dp: nothing here depends on how long a word is in any language.
|
||||
Row {
|
||||
CardButton(Icons.Filled.FolderOpen, R.string.media_open_in_files) { actions.openInFiles(media) }
|
||||
CardButton(Icons.Filled.Download, R.string.download) { actions.download(media) }
|
||||
CardButton(Icons.Filled.Share, R.string.report_share) { actions.share(media) }
|
||||
CardButton(Icons.AutoMirrored.Filled.OpenInNew, R.string.files_open_with) { actions.openWith(media) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The file's name on one line (its middle gives) and what is known of it on the next. */
|
||||
@Composable
|
||||
private fun MediaWords(media: GeneratedMedia) {
|
||||
val palette = LocalPalette.current
|
||||
Text(media.title, style = MaterialTheme.typography.bodyLarge, color = palette.ink, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)
|
||||
Text(mediaFacts(media), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
|
||||
/**
|
||||
* A file as a row: a mark of 48 dp -- Play for sound and video, Open for a PDF, else the kind's
|
||||
* icon -- and the file's words, which give.
|
||||
*/
|
||||
@Composable
|
||||
private fun MediaRow(media: GeneratedMedia, actions: MediaActions) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
Modifier.fillMaxWidth().border(1.dp, palette.border, CardShape).padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
val filled = IconButtonDefaults.filledIconButtonColors(containerColor = palette.accent, contentColor = palette.accentInk)
|
||||
when (media.view) {
|
||||
MediaView.Video, MediaView.Sound -> FilledIconButton(onClick = { actions.play(media) }, colors = filled, modifier = Modifier.size(48.dp)) {
|
||||
Icon(Icons.Filled.PlayArrow, contentDescription = stringResource(R.string.play))
|
||||
}
|
||||
|
||||
MediaView.Document -> FilledIconButton(onClick = { actions.view(media) }, colors = filled, modifier = Modifier.size(48.dp)) {
|
||||
Icon(mediaIcon(media.kind), contentDescription = stringResource(R.string.viewer_open))
|
||||
}
|
||||
|
||||
MediaView.Picture, MediaView.Details -> Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
||||
Icon(mediaIcon(media.kind), contentDescription = null, tint = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) { MediaWords(media) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CardButton(icon: ImageVector, label: Int, onClick: () -> Unit) {
|
||||
IconButton(onClick = onClick) { Icon(icon, contentDescription = stringResource(label), tint = LocalPalette.current.inkMuted) }
|
||||
}
|
||||
|
||||
/** The word for where a job stands; a state this app does not know is said as the server says it. */
|
||||
@Composable
|
||||
internal fun jobState(state: String): String = when (state) {
|
||||
"queued" -> stringResource(R.string.job_queued)
|
||||
"running" -> stringResource(R.string.job_running)
|
||||
"done" -> stringResource(R.string.job_done)
|
||||
"failed" -> stringResource(R.string.job_failed)
|
||||
"cancelled" -> stringResource(R.string.job_cancelled)
|
||||
"expired" -> stringResource(R.string.job_expired)
|
||||
else -> state
|
||||
}
|
||||
|
||||
/**
|
||||
* A generation that takes minutes, on the card of the call that started it: what is being made,
|
||||
* where it stands and for how long, and Cancel while it is under way. One that ended without a
|
||||
* file says why in the server's own sentence. The mark keeps its 48 dp and Cancel its own width;
|
||||
* the words between them give.
|
||||
*/
|
||||
@Composable
|
||||
fun JobCard(seen: JobSeen, actions: MediaActions, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val still = LocalInspectionMode.current
|
||||
val job = seen.job
|
||||
var now by remember { mutableLongStateOf(if (still) seen.at else SystemClock.elapsedRealtime()) }
|
||||
// The clock on the card runs on the phone between two reads of the job.
|
||||
LaunchedEffect(job.id, job.underWay) {
|
||||
while (job.underWay && !still) {
|
||||
now = SystemClock.elapsedRealtime()
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
Row(
|
||||
modifier.widthIn(max = 480.dp).fillMaxWidth().border(1.dp, palette.border, CardShape).padding(start = 12.dp, end = 4.dp, top = 10.dp, bottom = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
||||
when {
|
||||
// A wheel that never ends never lets a screenshot be taken: a still mark there.
|
||||
job.underWay && !still -> CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(24.dp))
|
||||
|
||||
job.underWay -> Icon(Icons.Filled.HourglassEmpty, contentDescription = null, tint = palette.inkMuted)
|
||||
|
||||
job.unsuccessful -> Icon(
|
||||
Icons.Filled.ErrorOutline,
|
||||
contentDescription = null,
|
||||
tint = if (job.state ==
|
||||
"failed"
|
||||
) {
|
||||
palette.danger
|
||||
} else {
|
||||
palette.inkMuted
|
||||
},
|
||||
)
|
||||
|
||||
else -> Icon(mediaIcon(job.kind), contentDescription = null, tint = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
listOf(mediaKind(job.kind), jobState(job.state)).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = palette.ink,
|
||||
)
|
||||
val elapsed = seen.elapsed(now)
|
||||
val facts = listOfNotNull(
|
||||
if (elapsed >
|
||||
0
|
||||
) {
|
||||
playTime((elapsed * 1000).coerceAtMost(Int.MAX_VALUE.toLong()).toInt())
|
||||
} else {
|
||||
null
|
||||
},
|
||||
job.source.ifBlank { null },
|
||||
)
|
||||
if (facts.isNotEmpty()) {
|
||||
Text(
|
||||
facts.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
// Why it was not made, in the instance's words: a sentence for the person, shown whole.
|
||||
if (job.unsuccessful && job.error.isNotBlank()) {
|
||||
Text(
|
||||
job.error,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (job.state == "failed") palette.danger else palette.inkMuted,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (job.underWay) {
|
||||
TextButton(onClick = { actions.cancel(job) }) { Text(stringResource(R.string.cancel)) }
|
||||
} else {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a call that made media leaves in the reply, always in view: its file's card; or its
|
||||
* job's card, which becomes the file's once the job is done.
|
||||
*/
|
||||
@Composable
|
||||
fun CallMedia(media: GeneratedMedia?, image: GeneratedImage?, job: JobSeen?, chat: ChatMedia) {
|
||||
if (media != null) MediaCard(media, image, chat.actions)
|
||||
if (job != null) {
|
||||
val result = job.job.result
|
||||
if (result != null && job.job.state == MediaJob.DONE) MediaCard(result, null, chat.actions) else JobCard(job, chat.actions)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaJobRef
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
|
||||
// A chat's long generations as the chat keeps them. There is no stream frame for a job -- a chat
|
||||
// has no stream while no reply is being written -- so the jobs under way are read again every few
|
||||
// seconds while the chat is in front, and the chat is read again when one of them has woken it.
|
||||
|
||||
/** A job as it was last read, and when ([at], the phone's uptime clock; 0: known only from the call). */
|
||||
data class JobSeen(val job: MediaJob, val at: Long = 0) {
|
||||
/** How long it has taken, in seconds, at [now]: counted on from the read while it is under way. */
|
||||
fun elapsed(now: Long): Long {
|
||||
val said = job.seconds.toLong().coerceAtLeast(0)
|
||||
return if (job.underWay && at > 0 && now > at) said + (now - at) / 1000 else said
|
||||
}
|
||||
}
|
||||
|
||||
/** How often jobs under way are read again. */
|
||||
const val JOB_POLL_MS = 3000L
|
||||
|
||||
/** How many more reads a job that has ended is given to say that the chat was told. */
|
||||
const val TELL_ROUNDS = 20
|
||||
|
||||
private fun calls(steps: List<Step>): Sequence<ToolCall> {
|
||||
fun all(call: ToolCall): Sequence<ToolCall> = sequenceOf(call) + call.children.orEmpty().asSequence().flatMap { all(it) }
|
||||
return steps.asSequence().flatMap { it.calls.asSequence() }.flatMap { all(it) }
|
||||
}
|
||||
|
||||
/** Every job the calls of these messages (and of the steps being written, [live]) started, each once, in the order the calls come. */
|
||||
fun jobRefsOf(messages: List<Message>, live: List<Step> = emptyList()): List<MediaJobRef> {
|
||||
val all = messages.asSequence().flatMap { calls(it.steps) } + calls(live)
|
||||
return all.mapNotNull { it.mediaJob?.takeIf { ref -> ref.id.isNotBlank() } }.distinctBy { it.id }.toList()
|
||||
}
|
||||
|
||||
/** The jobs this chat's calls started (the reply being written included). */
|
||||
val ChatState.jobRefs: List<MediaJobRef> get() = jobRefsOf(messages, live?.shown.orEmpty())
|
||||
|
||||
/**
|
||||
* A job that has ended and has not said yet that the chat was told: the reply about it is still
|
||||
* to come, so it is read a few more times. A cancelled job wakes nobody.
|
||||
*/
|
||||
fun awaitsTelling(job: MediaJob): Boolean = !job.underWay && !job.told && job.state != MediaJob.CANCELLED
|
||||
|
||||
/**
|
||||
* The jobs to read again: the ones a call names that were never read (the call's own word is
|
||||
* from the moment it returned), and the ones under way. A job that has ended is left alone.
|
||||
*/
|
||||
fun ChatState.jobsToRead(): List<String> {
|
||||
val named = jobRefs.map { it.id }.filter { mediaJobs[it]?.let { seen -> seen.at == 0L || seen.job.underWay } ?: true }
|
||||
val known = mediaJobs.values.filter { it.job.underWay }.map { it.job.id }
|
||||
return (named + known).distinct()
|
||||
}
|
||||
|
||||
/** [jobs], read at [at], among what the chat knows of its jobs. */
|
||||
fun ChatState.withJobs(jobs: List<MediaJob>, at: Long): ChatState =
|
||||
if (jobs.isEmpty()) this else copy(mediaJobs = mediaJobs + jobs.filter { it.id.isNotBlank() }.associate { it.id to JobSeen(it, at) })
|
||||
|
||||
/**
|
||||
* Whether a read says the chat was woken since the last one: the job was known and had not told
|
||||
* the chat, and now has. Then there is a reply this app did not start, and the transcript is
|
||||
* read again. A job first heard of already told is part of the transcript that was just read.
|
||||
*/
|
||||
fun woke(before: MediaJob?, after: MediaJob): Boolean = before != null && !before.told && after.told
|
||||
|
||||
/** What a call's job is drawn from: what was read of it, else the call's own word. */
|
||||
fun ChatMedia.job(ref: MediaJobRef): JobSeen = jobs[ref.id] ?: JobSeen(MediaJob.of(ref))
|
||||
@@ -0,0 +1,46 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import eu.llembas.android.api.DeviceFile
|
||||
import eu.llembas.android.api.Mention
|
||||
|
||||
// The composer's `@`: what is being asked for is the `@word` the text ends with. The field's
|
||||
// cursor is not followed -- a mention is offered for what is typed last, which is where typing
|
||||
// on a phone is.
|
||||
|
||||
/** A file on a linked device, as the `@` list holds it beside the server's kinds: put into the text as `@path`, never attached. */
|
||||
const val MENTION_DEVICE = "device"
|
||||
|
||||
/**
|
||||
* The `@` word [text] ends with, without the `@` (empty right after it), or null when it ends
|
||||
* with none: the `@` must open a word (so an e-mail address is not one), and the word holds no
|
||||
* space yet.
|
||||
*/
|
||||
fun mentionQuery(text: String): String? {
|
||||
val at = text.lastIndexOf('@')
|
||||
if (at < 0 || (at > 0 && !text[at - 1].isWhitespace())) return null
|
||||
return text.substring(at + 1).takeIf { word -> word.none { it.isWhitespace() } }
|
||||
}
|
||||
|
||||
/** [text] without the `@word` it ends with: what stays when the mention became an attachment. */
|
||||
fun withoutMention(text: String): String = if (mentionQuery(text) == null) text else text.substring(0, text.lastIndexOf('@'))
|
||||
|
||||
/** [text] with the `@word` it ends with made `@path` and a space: a device's file, which the device reads. */
|
||||
fun withMention(text: String, path: String): String = if (mentionQuery(text) == null) text else text.substring(0, text.lastIndexOf('@')) + "@" + path + " "
|
||||
|
||||
/** The most entries the `@` list shows. */
|
||||
const val MENTION_LIMIT = 50
|
||||
|
||||
/** The longest path a device's file may have to be offered. */
|
||||
const val MENTION_PATH = 512
|
||||
|
||||
/**
|
||||
* A device's file as an entry of the `@` list: its name, and its path as the detail. Null for
|
||||
* one that is not offered: its path goes into the message as it is, so a path with a line
|
||||
* break or another control character in it -- which the one-line row would not show -- or one
|
||||
* too long to be a path is left out.
|
||||
*/
|
||||
fun DeviceFile.asMention(): Mention? {
|
||||
if (path.isBlank() || path.length > MENTION_PATH || path.any { it.isISOControl() }) return null
|
||||
val shown = name.filterNot { it.isISOControl() }.take(MENTION_PATH).ifBlank { path }
|
||||
return Mention(kind = MENTION_DEVICE, path = path, name = shown, detail = if (kind == "dir") "$path/" else path)
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.titleAmong
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
@@ -99,12 +100,15 @@ fun ModelPickerContent(models: List<ModelInfo>, current: String?, onPick: (Strin
|
||||
modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
)
|
||||
LazyColumn(Modifier.fillMaxWidth().padding(bottom = 16.dp)) {
|
||||
items(models, key = { it.id }) { m ->
|
||||
val chosen = m.id == current
|
||||
// [current] is the key of the row in use, looked up by the caller, who knows how the name
|
||||
// was said: a chat's `model_ref` that is not in the list ticks no row, never one with that id.
|
||||
val inUse = current
|
||||
items(models.distinctBy { it.key }, key = { it.key }) { m ->
|
||||
val chosen = m.key == inUse
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onPick(m.id) }
|
||||
.clickable { onPick(m.key) }
|
||||
.heightIn(min = 72.dp)
|
||||
.padding(horizontal = 24.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -112,7 +116,7 @@ fun ModelPickerContent(models: List<ModelInfo>, current: String?, onPick: (Strin
|
||||
ModelAvatar(m, m.id, size = 44.dp)
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(m.name.ifBlank { m.id }, style = MaterialTheme.typography.titleMedium)
|
||||
Text(m.titleAmong(models), style = MaterialTheme.typography.titleMedium)
|
||||
modelNotes(m).takeIf { it.isNotEmpty() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.app.KeyguardManager
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.PhoneAndroid
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.FilterChipDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.actions.ActionRunner
|
||||
import eu.llembas.android.actions.Args
|
||||
import eu.llembas.android.actions.NavApp
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.PhoneResult
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
|
||||
/** The actions a map app carries out. */
|
||||
val NAV_ACTIONS = setOf("navigate", "add_stop", "search_nearby", "stop_navigation")
|
||||
|
||||
/** What the card shows of a phone card while it is being carried out. */
|
||||
data class PhoneCardState(val running: Boolean = false, val locked: Boolean = false, val error: String? = null)
|
||||
|
||||
/**
|
||||
* A `phone_action` card (spec 3.6.0) with the phone behind it: Do it carries the action out
|
||||
* ([ActionRunner]) and answers what happened -- done, or failed and why; Cancel answers declined.
|
||||
* Never while the phone is locked: Do it says to unlock first. Used by the chat's card sheet and
|
||||
* by the assistant's sheet alike.
|
||||
*/
|
||||
@Composable
|
||||
fun PhoneCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val prefs by context.lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
val installed = remember { NavApp.installedApps(context) }
|
||||
var state by remember(card.id) { mutableStateOf(PhoneCardState()) }
|
||||
val item = card.items.firstOrNull() ?: return
|
||||
val phone = item.phone ?: JsonObject(emptyMap())
|
||||
PhoneCardContent(
|
||||
phone = phone,
|
||||
navApps = installed,
|
||||
chosen = NavApp.chosen(prefs.navApp, installed),
|
||||
state = state,
|
||||
onDo = { app ->
|
||||
if (context.getSystemService(KeyguardManager::class.java).isKeyguardLocked) {
|
||||
state = state.copy(locked = true)
|
||||
return@PhoneCardContent
|
||||
}
|
||||
state = PhoneCardState(running = true)
|
||||
scope.launch {
|
||||
val action = (phone["action"] as? JsonPrimitive)?.content.orEmpty()
|
||||
val outcome = ActionRunner.run(context, action, Args(phone), app, askOsmAnd = prefs.osmandInfo)
|
||||
state = PhoneCardState(error = outcome.message.takeIf { outcome.status.wire == "failed" })
|
||||
onAnswer(CardAnswer(result = PhoneResult(outcome.status.wire, outcome.message)))
|
||||
}
|
||||
},
|
||||
onDecline = { onAnswer(CardAnswer(result = PhoneResult("declined"))) },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The card from its state alone (what the screenshot tests draw): the phone's icon and "Do this
|
||||
* on your phone?", the model's one line ([phone]'s `summary`), how it will be done and its facts,
|
||||
* the map app to use when Settings leaves it open ([chosen] null, more than one installed), and
|
||||
* Cancel / Do it -- each at least 48 dp, the line above them free to wrap.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun PhoneCardContent(
|
||||
phone: JsonObject,
|
||||
navApps: List<NavApp>,
|
||||
chosen: NavApp?,
|
||||
state: PhoneCardState,
|
||||
onDo: (NavApp?) -> Unit = {},
|
||||
onDecline: () -> Unit = {},
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val action = (phone["action"] as? JsonPrimitive)?.content.orEmpty()
|
||||
val summary = (phone["summary"] as? JsonPrimitive)?.content.orEmpty().ifBlank { action }
|
||||
val nav = action in NAV_ACTIONS
|
||||
var picked by remember(chosen) { mutableStateOf(chosen ?: navApps.singleOrNull()) }
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.PhoneAndroid, contentDescription = null, tint = palette.accent, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(stringResource(R.string.action_card_title), style = MaterialTheme.typography.labelLarge, color = palette.accent)
|
||||
}
|
||||
Text(summary, style = MaterialTheme.typography.titleMedium)
|
||||
Text(howLine(action, picked), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
phoneFacts(phone).takeIf { it.isNotBlank() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
if (nav && chosen == null && navApps.size > 1) {
|
||||
Text(stringResource(R.string.nav_app_pick), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
navApps.forEach { app ->
|
||||
FilterChip(
|
||||
selected = picked == app,
|
||||
onClick = { picked = app },
|
||||
label = { Text(stringResource(if (app == NavApp.OsmAnd) R.string.nav_app_osmand else R.string.nav_app_google)) },
|
||||
colors = FilterChipDefaults.filterChipColors(selectedContainerColor = palette.accentSoft),
|
||||
modifier = Modifier.heightIn(min = 40.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nav && picked == NavApp.GoogleMaps && action in setOf("add_stop", "stop_navigation")) {
|
||||
Text(
|
||||
stringResource(if (action == "add_stop") R.string.action_google_add_stop else R.string.action_google_no_stop),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.warning,
|
||||
)
|
||||
}
|
||||
when {
|
||||
state.locked -> Text(stringResource(R.string.action_unlock), style = MaterialTheme.typography.bodyMedium, color = palette.warning)
|
||||
|
||||
state.error != null -> Text(
|
||||
stringResource(R.string.action_failed, state.error),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.danger,
|
||||
)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
|
||||
TextButton(onClick = onDecline, enabled = !state.running, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Button(
|
||||
onClick = { onDo(picked) },
|
||||
enabled = !state.running && (!nav || picked != null),
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
) { Text(stringResource(if (state.running) R.string.action_running else R.string.action_do)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How the action will be done, in a sentence: which kind of app, and what is left to the person. */
|
||||
@Composable
|
||||
private fun howLine(action: String, app: NavApp?): String = when (action) {
|
||||
"alarm", "timer" -> stringResource(R.string.action_line_clock)
|
||||
|
||||
"calendar_event" -> stringResource(R.string.action_line_calendar)
|
||||
|
||||
"sms_draft", "email_draft" -> stringResource(R.string.action_line_draft)
|
||||
|
||||
"dial" -> stringResource(R.string.action_line_dial)
|
||||
|
||||
"navigate", "add_stop", "search_nearby", "stop_navigation" ->
|
||||
stringResource(
|
||||
R.string.action_line_map,
|
||||
stringResource(
|
||||
if (app ==
|
||||
NavApp.OsmAnd
|
||||
) {
|
||||
R.string.nav_app_osmand
|
||||
} else if (app == NavApp.GoogleMaps) {
|
||||
R.string.nav_app_google
|
||||
} else {
|
||||
R.string.nav_app
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
"media", "torch" -> stringResource(R.string.action_line_now)
|
||||
|
||||
"settings_panel" -> stringResource(R.string.action_line_settings)
|
||||
|
||||
"automation_intent" -> stringResource(R.string.action_line_automation)
|
||||
|
||||
else -> stringResource(R.string.action_line_open)
|
||||
}
|
||||
|
||||
/**
|
||||
* The action's facts as one line, values only, in the order the spec lists the fields: what the
|
||||
* person checks before Do it ("07:00 · mon tue wed thu fri · Work"). A place is its name and,
|
||||
* when it has one, what the map app will search, or its coordinates.
|
||||
*/
|
||||
fun phoneFacts(phone: JsonObject): String {
|
||||
fun place(e: JsonElement?): String? {
|
||||
val o = e as? JsonObject ?: return (e as? JsonPrimitive)?.content
|
||||
val name = (o["name"] as? JsonPrimitive)?.content.orEmpty()
|
||||
val query = (o["query"] as? JsonPrimitive)?.content.orEmpty()
|
||||
val lat = (o["lat"] as? JsonPrimitive)?.content
|
||||
val lon = (o["lon"] as? JsonPrimitive)?.content
|
||||
val where = query.ifBlank { if (lat != null && lon != null) "$lat, $lon" else "" }
|
||||
return listOf(name, where).filter { it.isNotBlank() }.distinct().let {
|
||||
if (it.size == 2) "${it[0]} (${it[1]})" else it.firstOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
fun value(key: String, e: JsonElement?): String? = when {
|
||||
e == null -> null
|
||||
key in setOf("destination", "stop") -> place(e)
|
||||
key == "stops" -> (e as? JsonArray)?.mapNotNull { place(it) }?.joinToString(" → ")?.ifBlank { null }
|
||||
e is JsonArray -> e.mapNotNull { (it as? JsonPrimitive)?.content }.joinToString(" ").ifBlank { null }
|
||||
e is JsonObject -> e.entries.joinToString(", ") { (k, v) -> "$k=${(v as? JsonPrimitive)?.content.orEmpty()}" }.ifBlank { null }
|
||||
e is JsonPrimitive -> e.content.takeIf { it.isNotBlank() && it != "false" && it != "true" }
|
||||
else -> null
|
||||
}
|
||||
return FACT_ORDER.mapNotNull { key -> value(key, phone[key]) }.joinToString(" · ")
|
||||
}
|
||||
|
||||
private val FACT_ORDER = listOf(
|
||||
"time", "days", "seconds", "label", "title", "start", "end", "location", "to", "cc", "subject", "number",
|
||||
"stops", "stop", "destination", "mode", "query", "near", "app", "url", "command", "panel", "task", "values",
|
||||
)
|
||||
@@ -6,6 +6,7 @@ import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import eu.llembas.android.api.MediaFor
|
||||
import eu.llembas.android.assist.AssistController
|
||||
import eu.llembas.android.assist.Speaker
|
||||
import eu.llembas.android.lembas
|
||||
@@ -23,7 +24,15 @@ import kotlinx.coroutines.launch
|
||||
* shows a button that can only fail.
|
||||
*/
|
||||
@Stable
|
||||
class ReadAloud(private val context: Context, private val scope: CoroutineScope, private val onError: (String) -> Unit) {
|
||||
class ReadAloud(
|
||||
private val context: Context,
|
||||
private val scope: CoroutineScope,
|
||||
/** Which chat is read from, asked at each reading: its connection may have a voice of its own. */
|
||||
private val media: () -> MediaFor = { MediaFor.DEFAULT },
|
||||
/** Another source read it than the chat's own: its name. */
|
||||
private val onFallback: (String) -> Unit = {},
|
||||
private val onError: (String) -> Unit,
|
||||
) {
|
||||
private val speaker = Speaker(context)
|
||||
private var job: Job? = null
|
||||
|
||||
@@ -45,7 +54,9 @@ class ReadAloud(private val context: Context, private val scope: CoroutineScope,
|
||||
job = scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: return@launch
|
||||
speaker.play(api.speech(AssistController.plain(markdown)))
|
||||
val spoken = api.speech(AssistController.plain(markdown), media())
|
||||
spoken.fallback?.let(onFallback)
|
||||
speaker.play(spoken.audio)
|
||||
speaker.playing.first { !it }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
/**
|
||||
* The reads of one thing (a chat's transcript) that several pieces of news ask for, one at a
|
||||
* time and none twice for the same news. Whoever learns something that needs a read takes a
|
||||
* [mark] at that moment -- before waiting for anything -- and asks [since] it; a read that began
|
||||
* after the mark and came back has seen what the mark's news was about, so the asker's own is
|
||||
* not made. A burst of frames, or a return to the front that several watchers notice, is then
|
||||
* one read; news that arrives while a read is under way is newer than that read, and gets its own.
|
||||
*/
|
||||
class Reads {
|
||||
private val one = Mutex()
|
||||
|
||||
/** How many reads have begun. */
|
||||
private var begun = 0L
|
||||
|
||||
/** The last read that came back with an answer, by its number. */
|
||||
private var answered = 0L
|
||||
|
||||
/** The moment some news was learned: every read that begins from now on covers it. */
|
||||
fun mark(): Long = begun
|
||||
|
||||
/**
|
||||
* [read], unless a read that began after [mark] has already answered, or [wanted] says -- once
|
||||
* it is this asker's turn -- that nothing is asked for any more. [read] says whether it got
|
||||
* an answer; one that did not covers nobody. True when [read] ran.
|
||||
*/
|
||||
suspend fun since(mark: Long, wanted: () -> Boolean = { true }, read: suspend () -> Boolean): Boolean = one.withLock {
|
||||
if (answered > mark || !wanted()) return@withLock false
|
||||
val mine = ++begun
|
||||
if (read()) answered = mine
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -13,11 +13,14 @@ import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
@@ -41,10 +44,13 @@ import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.Movie
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material.icons.filled.Psychology
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.SelectAll
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material.icons.filled.Web
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
@@ -60,6 +66,7 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
@@ -82,12 +89,20 @@ import androidx.compose.ui.unit.sp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.api.Waiting
|
||||
import eu.llembas.android.api.ending
|
||||
import eu.llembas.android.api.replyModel
|
||||
import eu.llembas.android.api.shownMarkdown
|
||||
import eu.llembas.android.api.waiting
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.Segment
|
||||
import eu.llembas.android.ui.highlight
|
||||
import eu.llembas.android.ui.pageProjection
|
||||
import eu.llembas.android.ui.progressLineOf
|
||||
import eu.llembas.android.ui.splitFences
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
@@ -101,13 +116,32 @@ private val Bubble = RoundedCornerShape(topStart = 20.dp, topEnd = 6.dp, bottomS
|
||||
private val Block = RoundedCornerShape(12.dp)
|
||||
private val Pill = RoundedCornerShape(50)
|
||||
|
||||
/** A reply's foot: the gap above it, and the height of its row of buttons (an icon button's 48 dp). */
|
||||
private val FootTop = 2.dp
|
||||
private val FootHeight = 48.dp
|
||||
|
||||
/** A waiting message's two buttons: a tap target's height. */
|
||||
private val WaitingButton = 48.dp
|
||||
|
||||
/**
|
||||
* The person's turn: their words in a bubble on the right (never markdown), what they attached
|
||||
* above it as thumbnails. A long press offers Copy and, where the turn can still change, Edit.
|
||||
*
|
||||
* A message that waits says how it waits in words under the bubble, and -- where [onSendNow]
|
||||
* and [onDiscard] are given, which only the chat's own screen does -- offers the two things a
|
||||
* person does with it. They rest while [busy]: one of them is being asked of the instance.
|
||||
*/
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@OptIn(ExperimentalFoundationApi::class, ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun UserMessage(message: Message, canEdit: Boolean, onEdit: () -> Unit, modifier: Modifier = Modifier) {
|
||||
fun UserMessage(
|
||||
message: Message,
|
||||
canEdit: Boolean,
|
||||
onEdit: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
busy: Boolean = false,
|
||||
onSendNow: (() -> Unit)? = null,
|
||||
onDiscard: (() -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val copy = LocalCopy.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
@@ -154,18 +188,55 @@ fun UserMessage(message: Message, canEdit: Boolean, onEdit: () -> Unit, modifier
|
||||
}
|
||||
}
|
||||
}
|
||||
if (message.queued) {
|
||||
// The server's queued progress ("Queued, 2 ahead · 12s") where it sends one.
|
||||
message.waiting?.let { waiting ->
|
||||
// How it waits, in words. Queued behind a reply: the server's progress ("Queued: 2
|
||||
// ahead · 12s") where it sends one. Not for one a linked computer was handed: that
|
||||
// one waits for the person or for the computer, not for its turn here.
|
||||
Text(
|
||||
progressLineOf(message.progress) ?: stringResource(R.string.queued),
|
||||
when (waiting) {
|
||||
Waiting.Unsure -> stringResource(R.string.fate_unknown)
|
||||
Waiting.Carried -> stringResource(R.string.fate_carried)
|
||||
Waiting.Queued -> progressLineOf(message.progress) ?: stringResource(R.string.queued)
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
color = if (waiting == Waiting.Unsure) palette.warning else palette.inkFaint,
|
||||
modifier = Modifier.padding(top = 4.dp, end = 4.dp),
|
||||
)
|
||||
if (onSendNow != null && onDiscard != null) {
|
||||
// Two buttons of unknown width (eight languages, any type size): they share a
|
||||
// row that wraps, each a full tap target, from the bubble's edge.
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.End)) {
|
||||
TextButton(onClick = onDiscard, enabled = !busy, modifier = Modifier.heightIn(min = WaitingButton)) {
|
||||
Text(stringResource(R.string.discard))
|
||||
}
|
||||
TextButton(onClick = onSendNow, enabled = !busy, modifier = Modifier.heightIn(min = WaitingButton)) {
|
||||
Text(stringResource(R.string.send_now))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A line the server wrote in the person's place (a schedule's instruction, what opens a report's
|
||||
* conversation): a quiet note across the width, a few lines of it -- never the person's bubble,
|
||||
* and never markdown.
|
||||
*/
|
||||
@Composable
|
||||
fun MachineNote(text: String, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
if (text.isBlank()) return
|
||||
Text(
|
||||
text.trim(),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 4,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = modifier.fillMaxWidth().padding(horizontal = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The model's turn, full width and without a bubble: its steps (thinking and tools folded into
|
||||
* chips that open), its words as markdown, and under it Copy, Regenerate and what it cost. While
|
||||
@@ -181,6 +252,8 @@ fun AssistantMessage(
|
||||
onRegenerate: () -> Unit,
|
||||
onShow: ((ShowCard) -> Unit)?,
|
||||
modifier: Modifier = Modifier,
|
||||
/** The models offered here: a reply by one of two that share an id says its connection. */
|
||||
models: List<ModelInfo> = emptyList(),
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val copy = LocalCopy.current
|
||||
@@ -221,13 +294,24 @@ fun AssistantMessage(
|
||||
}
|
||||
}
|
||||
if (writing) {
|
||||
Writing(Modifier.padding(top = if (steps.isEmpty()) 0.dp else 8.dp), withLine = steps.isEmpty())
|
||||
// Once there is something written, the pulse stands in the finished reply's foot --
|
||||
// the same top and the same height as its row of buttons -- so the reply ending
|
||||
// does not change the row's height under a person at the end of it.
|
||||
if (steps.isEmpty()) Writing(withLine = true) else Writing(Modifier.padding(top = FootTop), minHeight = FootHeight)
|
||||
} else {
|
||||
message.error?.let {
|
||||
Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(top = 8.dp))
|
||||
// How a reply that did not finish ended (display.md §4): the progress text alone --
|
||||
// "Stopped: by you", "Failed: …" -- staying at the end of the reply; an error in
|
||||
// the error colour, a stop muted. Nothing else says it a second time.
|
||||
message.ending()?.let { end ->
|
||||
Text(
|
||||
progressLineOf(end, withElapsed = false) ?: message.error.orEmpty(),
|
||||
color = if (end.phase == "failed") palette.danger else palette.inkMuted,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.padding(top = 8.dp),
|
||||
)
|
||||
}
|
||||
// The actions and the foot share one row: the icons keep their 48 dp, the foot gives.
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = FootTop)) {
|
||||
if (words.isNotBlank()) {
|
||||
IconButton(onClick = { copy(words) }) {
|
||||
Icon(
|
||||
@@ -259,7 +343,7 @@ fun AssistantMessage(
|
||||
)
|
||||
}
|
||||
}
|
||||
footLine(message)?.let { line ->
|
||||
footLine(message, models)?.let { line ->
|
||||
Text(
|
||||
line,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
@@ -286,15 +370,27 @@ fun AssistantMessage(
|
||||
}
|
||||
|
||||
/** A reply's own words, as the person would copy them: its text steps, in order. */
|
||||
fun replyText(message: Message): String =
|
||||
message.steps.filter { it.kind == "text" }.mapNotNull { it.markdown }.joinToString("\n\n").ifBlank { message.text.orEmpty() }
|
||||
fun replyText(message: Message): String = pageProjection(
|
||||
message.steps.mapNotNull { step ->
|
||||
when (step.kind) {
|
||||
"text" -> step.shownMarkdown
|
||||
"page" -> "[page: ${step.title.orEmpty()}]"
|
||||
else -> null
|
||||
}
|
||||
}.joinToString("\n\n").ifBlank { message.text.orEmpty() },
|
||||
untitled = PAGE_UNTITLED,
|
||||
)
|
||||
|
||||
/** `pages.untitled`, for the text that is copied or read aloud (the card says it in the app's language). */
|
||||
private const val PAGE_UNTITLED = "Page"
|
||||
|
||||
/** What a finished reply cost, in one quiet line: model, tokens, speed. Null when nothing was counted. */
|
||||
private fun footLine(message: Message): String? {
|
||||
val m = message.metrics ?: return message.model
|
||||
if (m.completionTokens == 0 && m.elapsedMs == 0L) return message.model
|
||||
internal fun footLine(message: Message, models: List<ModelInfo> = emptyList()): String? {
|
||||
val model = models.replyModel(message.modelRef, message.model)
|
||||
val m = message.metrics ?: return model
|
||||
if (m.completionTokens == 0 && m.elapsedMs == 0L) return model
|
||||
return buildList {
|
||||
message.model?.let { add(it) }
|
||||
model?.let { add(it) }
|
||||
if (m.completionTokens > 0) add("${if (m.estimated) "~" else ""}${m.completionTokens} tok")
|
||||
if (m.tokPerSecond > 0) add("${"%.1f".format(m.tokPerSecond)} tok/s")
|
||||
}.joinToString(" · ").ifBlank { null }
|
||||
@@ -302,13 +398,13 @@ private fun footLine(message: Message): String? {
|
||||
|
||||
/** Three dots that breathe, and (before the first word) the loading line beside them. */
|
||||
@Composable
|
||||
fun Writing(modifier: Modifier = Modifier, withLine: Boolean = false) {
|
||||
fun Writing(modifier: Modifier = Modifier, withLine: Boolean = false, minHeight: Dp = 32.dp) {
|
||||
val palette = LocalPalette.current
|
||||
// Still in a preview or a screenshot, where an animation that never ends never lets the
|
||||
// picture be taken.
|
||||
val still = LocalInspectionMode.current
|
||||
val pulse = rememberInfiniteTransition(label = "writing")
|
||||
Row(modifier.heightIn(min = 32.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Row(modifier.heightIn(min = minHeight), verticalAlignment = Alignment.CenterVertically) {
|
||||
repeat(3) { i ->
|
||||
val alpha = if (still) {
|
||||
listOf(1f, 0.6f, 0.3f)[i]
|
||||
@@ -343,9 +439,19 @@ fun StepsCompact(steps: List<Step>, modifier: Modifier = Modifier, onShow: ((Sho
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
steps.forEach { step ->
|
||||
when (step.kind) {
|
||||
"thinking" -> ThinkingChip(step)
|
||||
"text" -> RichMarkdown(step.markdown.orEmpty(), onLongPress = onLongPress)
|
||||
// By its place in the reply, not by its turn in this loop: a chip the person
|
||||
// opened is the same chip when its step closes and others come after it.
|
||||
"thinking" -> key(step.index, step.kind) { ThinkingChip(step) }
|
||||
|
||||
// A closed step's pages are the server's to name (its `text`); in the step still
|
||||
// being written a page's fence is a page already, not source scrolling by.
|
||||
"text" -> RichMarkdown(step.shownMarkdown, onLongPress = onLongPress, pages = step.open)
|
||||
|
||||
// A page the server took out of the text as a step of its own: the same card.
|
||||
"page" -> PageCard(step.title.orEmpty())
|
||||
|
||||
"tools" -> ToolsChip(step, onShow)
|
||||
|
||||
"steer" -> step.messages.forEach { Steered(it.text) }
|
||||
}
|
||||
}
|
||||
@@ -354,18 +460,46 @@ fun StepsCompact(steps: List<Step>, modifier: Modifier = Modifier, onShow: ((Sho
|
||||
|
||||
/** Markdown with its fenced code taken out into [CodeBlock]s, each with its own Copy. */
|
||||
@Composable
|
||||
fun RichMarkdown(markdown: String, modifier: Modifier = Modifier, onLongPress: (() -> Unit)? = null) {
|
||||
val segments = remember(markdown) { splitFences(markdown) }
|
||||
fun RichMarkdown(markdown: String, modifier: Modifier = Modifier, onLongPress: (() -> Unit)? = null, pages: Boolean = false) {
|
||||
val segments = remember(markdown, pages) { splitFences(markdown, pages) }
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
segments.forEach { segment ->
|
||||
when (segment) {
|
||||
is Segment.Prose -> MarkdownText(segment.markdown, modifier = Modifier.fillMaxWidth(), onLongPress = onLongPress)
|
||||
is Segment.Code -> CodeBlock(segment.language, segment.code)
|
||||
is Segment.Page -> PageCard(segment.title)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A page in an answer (harness spec 3.8.0, `pages.md`): not drawn on a phone -- no web view, and
|
||||
* never its source. One quiet card says that there is one, by its title, and where it can be
|
||||
* seen. The title is a model's: plain text.
|
||||
*/
|
||||
@Composable
|
||||
fun PageCard(title: String, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
modifier.fillMaxWidth().clip(Block).border(1.dp, palette.border, Block).padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(Icons.Filled.Web, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
stringResource(R.string.page_note, title.ifBlank { stringResource(R.string.page_untitled) }),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.ink,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(stringResource(R.string.page_where), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A code block: its language and Copy above, the code below in its own sideways scroller. */
|
||||
@Composable
|
||||
fun CodeBlock(language: String, code: String, modifier: Modifier = Modifier) {
|
||||
@@ -391,8 +525,10 @@ fun CodeBlock(language: String, code: String, modifier: Modifier = Modifier) {
|
||||
}
|
||||
}
|
||||
HorizontalDivider(color = palette.codeBorder)
|
||||
// The fence's language in the theme's colours (ui/Highlight.kt); plain when it names none it reads.
|
||||
val shown = remember(code, language, palette) { highlight(code, language, palette) }
|
||||
Text(
|
||||
code,
|
||||
shown,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
@@ -444,7 +580,9 @@ private fun FoldChip(
|
||||
@Composable
|
||||
private fun ThinkingChip(step: Step) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(step.index, step.open) { mutableStateOf(false) }
|
||||
// Open only because the person opened it, and then it stays open: the step closing (the
|
||||
// thinking is over, the words begin) is not a reason to fold away what somebody is reading.
|
||||
var open by rememberSaveable(step.index) { mutableStateOf(false) }
|
||||
val label = if (step.open) stringResource(R.string.thinking) + "…" else stringResource(R.string.thought) + (step.label?.let { " $it" } ?: "")
|
||||
FoldChip(
|
||||
open = open,
|
||||
@@ -502,9 +640,20 @@ private fun ToolsChip(step: Step, onShow: ((ShowCard) -> Unit)?) {
|
||||
}
|
||||
}
|
||||
shows.forEach { call -> ToolCallBlock(call, onShow = onShow) }
|
||||
// A picture the instance made stays in view, like a `show` card: it is the answer.
|
||||
step.calls.mapNotNull { call -> call.image?.takeIf { it.id.isNotBlank() && call.status != "error" && call.error.isNullOrEmpty() } }
|
||||
.forEach { GeneratedPicture(it) }
|
||||
// What the instance made stays in view, like a `show` card: it is the answer. A picture as
|
||||
// before; in a chat's own screen also the file's card (a player, the ways to the file) and
|
||||
// the card of a generation still under way. Elsewhere -- the assistant's sheet, which may be
|
||||
// over the lock screen -- only the picture, as before.
|
||||
val media = LocalChatMedia.current
|
||||
step.calls.filter { it.status != "error" && it.error.isNullOrEmpty() }.forEach { call ->
|
||||
val image = call.image?.takeIf { it.id.isNotBlank() }
|
||||
if (media == null) {
|
||||
image?.let { GeneratedPicture(it) }
|
||||
} else {
|
||||
if (call.media == null) image?.let { GeneratedPicture(it) }
|
||||
CallMedia(call.media, image, call.mediaJob?.takeIf { it.id.isNotBlank() }?.let { media.job(it) }, media)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -555,7 +704,17 @@ private object Thumbnails {
|
||||
fun AttachmentTile(attachment: Attachment, side: Dp, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Box(modifier.size(side).clip(Block).background(palette.surfaceRaised).border(1.dp, palette.border, Block), contentAlignment = Alignment.Center) {
|
||||
// Sound and video the person attached are played, where a chat's screen has a player.
|
||||
val play = LocalChatMedia.current?.actions?.takeIf { attachment.kind == "audio" || attachment.kind == "video" }
|
||||
Box(
|
||||
modifier
|
||||
.size(side)
|
||||
.clip(Block)
|
||||
.background(palette.surfaceRaised)
|
||||
.border(1.dp, palette.border, Block)
|
||||
.then(if (play != null) Modifier.clickable(onClickLabel = stringResource(R.string.play)) { play.play(attachment) } else Modifier),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (attachment.image) {
|
||||
var image by remember(attachment.id) { mutableStateOf(Thumbnails.cached(attachment.id)) }
|
||||
val still = LocalInspectionMode.current
|
||||
@@ -568,7 +727,15 @@ fun AttachmentTile(attachment: Attachment, side: Dp, modifier: Modifier = Modifi
|
||||
}
|
||||
} else {
|
||||
Column(Modifier.padding(8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(Icons.Filled.Description, contentDescription = null, tint = palette.inkMuted)
|
||||
Icon(
|
||||
when (attachment.kind) {
|
||||
"audio" -> Icons.Filled.MusicNote
|
||||
"video" -> Icons.Filled.Movie
|
||||
else -> Icons.Filled.Description
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = if (play != null) palette.accent else palette.inkMuted,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
attachment.name,
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.ChatDetail
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Turn
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
|
||||
/**
|
||||
* A waiting message was sent now ([turn], the instance's answer): its row is the message as it
|
||||
* is after -- no longer waiting -- where it stood, and the reply started for it is the last row.
|
||||
* No row is there twice: the list's rows are keyed by id.
|
||||
*/
|
||||
fun ChatState.sentNow(turn: Turn): ChatState {
|
||||
val sent = turn.message
|
||||
val reply = turn.reply
|
||||
val rows = messages.filterNot { it.id == reply?.id }.map { if (it.id == sent?.id) sent else it }
|
||||
return copy(messages = rows + listOfNotNull(reply), lastSent = sent?.id ?: lastSent)
|
||||
}
|
||||
|
||||
/** A waiting message was discarded: its row is gone, and nothing else moved. */
|
||||
fun ChatState.discarded(id: String): ChatState = copy(messages = messages.filterNot { it.id == id })
|
||||
|
||||
/**
|
||||
* Whether a refusal says the screen showed a message as waiting that is not so any more, or
|
||||
* could not be acted on as shown: 409 (a reply is being written; the message no longer waits)
|
||||
* and 404 (it is not there). The chat is then read again. Anything else -- no network, a server
|
||||
* error -- says nothing about the message, and the row stays as it is.
|
||||
*/
|
||||
fun staleWaiting(e: Throwable): Boolean = e is ApiException && (e.status == 409 || e.status == 404)
|
||||
|
||||
/** A reply to follow, and whether the person asked for it from this screen. */
|
||||
data class Followed(val reply: String, val own: Boolean)
|
||||
|
||||
/**
|
||||
* Which reply is followed once a waiting message was sent now: the one the send started
|
||||
* ([reply]), as a reply the person asked for from this screen -- unless the chat, [read] after
|
||||
* the send, no longer holds it as being written. That happens by design: a linked computer
|
||||
* that still knew the message does not run it a second time, and the reply started for it is
|
||||
* removed. Then whatever else the read says is being written is followed, as nobody's.
|
||||
*/
|
||||
fun followedAfterSend(reply: String?, read: ChatDetail?): Followed? {
|
||||
if (reply != null && (read == null || read.live == reply || read.messages.any { it.id == reply && !it.complete })) {
|
||||
return Followed(reply, own = true)
|
||||
}
|
||||
return read?.live?.let { Followed(it, own = false) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The two things a person does with a message that waits, as the chat's screen does them. The
|
||||
* instance is asked through each action's own request; what the screen shows is [state].
|
||||
*
|
||||
* Sent: the row stops waiting at once, the chat is read ([read]; a chat on a linked computer
|
||||
* sorts the message to where it was sent), and the reply started for it is followed ([follow])
|
||||
* exactly as one the person asked for by typing. Discarded: the row is gone. Refused with a
|
||||
* 409 or a 404: the instance's sentence is said ([say]) and the chat is read again
|
||||
* ([catchUp]), because what the screen showed as waiting is not so any more. While one of the
|
||||
* two is under way for a message, [ChatState.acting] names it and its buttons rest.
|
||||
*/
|
||||
class WaitingActions(
|
||||
private val state: MutableStateFlow<ChatState>,
|
||||
private val read: suspend () -> ChatDetail?,
|
||||
private val follow: (Followed) -> Unit,
|
||||
private val say: (Throwable) -> Unit,
|
||||
private val catchUp: suspend () -> Unit,
|
||||
) {
|
||||
suspend fun sendNow(message: Message, send: suspend () -> Turn) = act(message) {
|
||||
val turn = send()
|
||||
state.update { it.sentNow(turn) }
|
||||
followedAfterSend(turn.reply?.id, read())?.let(follow)
|
||||
}
|
||||
|
||||
suspend fun discard(message: Message, withdraw: suspend () -> Unit) = act(message) {
|
||||
withdraw()
|
||||
state.update { it.discarded(message.id) }
|
||||
}
|
||||
|
||||
/** One action at a time: a second tap while the first is asked is not a second request. */
|
||||
private suspend fun act(message: Message, action: suspend () -> Unit) {
|
||||
if (state.value.acting != null) return
|
||||
state.update { it.copy(acting = message.id) }
|
||||
var stale = false
|
||||
try {
|
||||
action()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
say(e)
|
||||
stale = staleWaiting(e)
|
||||
} finally {
|
||||
state.update { if (it.acting == message.id) it.copy(acting = null) else it }
|
||||
}
|
||||
// After the buttons are free again: the read may wait for a reply being written here.
|
||||
if (stale) catchUp()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.CreateNewFolder
|
||||
import androidx.compose.material.icons.filled.DeleteForever
|
||||
import androidx.compose.material.icons.filled.DeleteSweep
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.FolderShared
|
||||
import androidx.compose.material.icons.filled.RestoreFromTrash
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileVersion
|
||||
import eu.llembas.android.api.TrashItem
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.scheduled.ScheduleLogic
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
// The file manager's smaller pages: a name, a yes or no, the folder to move or copy into, the
|
||||
// trash, and a file's versions. Each is drawn from its state alone.
|
||||
|
||||
/** Ask for a name: a new folder's, a new file's, or a new one for something that has one. */
|
||||
@Composable
|
||||
fun NameDialog(title: String, ask: String?, initial: String, confirm: String, onName: (String) -> Unit, onDismiss: () -> Unit) {
|
||||
var name by remember { mutableStateOf(initial) }
|
||||
val bad = FileKinds.badName(name)
|
||||
val problem: (@Composable () -> Unit)? = if (name.isNotEmpty() && bad) {
|
||||
{ Text(stringResource(R.string.files_bad_name)) }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(title) },
|
||||
text = {
|
||||
Column {
|
||||
ask?.let { Text(it, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(bottom = 12.dp)) }
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
singleLine = true,
|
||||
isError = name.isNotEmpty() && bad,
|
||||
supportingText = problem,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { onName(name.trim()) }, enabled = !bad && name.trim() != initial) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** A question with one thing to do and a way not to. */
|
||||
@Composable
|
||||
fun ConfirmDialog(text: String, confirm: String, onConfirm: () -> Unit, onDismiss: () -> Unit) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
text = { Text(text, style = MaterialTheme.typography.bodyLarge) },
|
||||
confirmButton = { TextButton(onClick = onConfirm) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** Where the folder picker is: the folders of [path], on their way or refused. */
|
||||
data class FolderPickState(
|
||||
val path: String = "/",
|
||||
val parent: String? = null,
|
||||
val folders: List<FileEntry> = emptyList(),
|
||||
val loading: Boolean = true,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Choosing a folder of the tree by walking to it: where something is moved or copied, or where
|
||||
* a share is saved. No path is typed. [hidden]: the things being moved, which cannot be their
|
||||
* own destination.
|
||||
*/
|
||||
@Composable
|
||||
fun FolderPicker(title: String, confirm: String, start: String, onPick: (String) -> Unit, onDismiss: () -> Unit, hidden: Set<String> = emptySet()) {
|
||||
val context = LocalContext.current
|
||||
var state by remember { mutableStateOf(FolderPickState(path = start)) }
|
||||
var asked by remember { mutableStateOf(start) }
|
||||
var again by remember { mutableIntStateOf(0) }
|
||||
var naming by remember { mutableStateOf(false) }
|
||||
var said by remember { mutableStateOf<String?>(null) }
|
||||
val scope = rememberCoroutineScope()
|
||||
LaunchedEffect(asked, again) {
|
||||
state = state.copy(loading = true, error = null)
|
||||
state = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
val listing = api.files(asked)
|
||||
FolderPickState(listing.path, listing.parent, listing.entries.filter { it.isFolder && it.path !in hidden }, loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state.copy(loading = false, error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
val up: () -> Unit = {
|
||||
val parent = state.parent
|
||||
if (parent != null) asked = parent else onDismiss()
|
||||
}
|
||||
Dialog(onDismissRequest = up, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
FolderPickContent(
|
||||
title,
|
||||
confirm,
|
||||
state,
|
||||
onOpen = { asked = it },
|
||||
onUp = up,
|
||||
onPick = { onPick(state.path) },
|
||||
onDismiss = onDismiss,
|
||||
onNewFolder = { naming = true },
|
||||
)
|
||||
}
|
||||
if (naming) {
|
||||
NameDialog(
|
||||
stringResource(R.string.folder_new),
|
||||
stringResource(R.string.files_new_folder_ask),
|
||||
"",
|
||||
stringResource(R.string.save),
|
||||
onName = { name ->
|
||||
naming = false
|
||||
val dir = state.path
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
api.makeFolder(dir, name)
|
||||
// Made, and walked into: it is most likely where the thing is meant to go.
|
||||
if (asked == FileKinds.child(dir, name)) again++ else asked = FileKinds.child(dir, name)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
said = context.filesSay(e)
|
||||
}
|
||||
}
|
||||
},
|
||||
onDismiss = { naming = false },
|
||||
)
|
||||
}
|
||||
said?.let { SaidDialog(it, onClose = { said = null }) }
|
||||
}
|
||||
|
||||
/** The folder picker's page: where it is, that folder's folders, and the one button that chooses the folder shown. */
|
||||
@Composable
|
||||
fun FolderPickContent(
|
||||
title: String,
|
||||
confirm: String,
|
||||
state: FolderPickState,
|
||||
onOpen: (String) -> Unit = {},
|
||||
onUp: () -> Unit = {},
|
||||
onPick: () -> Unit = {},
|
||||
onDismiss: () -> Unit = {},
|
||||
/** Make a folder in the one shown; null where the page cannot. */
|
||||
onNewFolder: (() -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
actions = {
|
||||
if (onNewFolder != null) {
|
||||
IconButton(onClick = onNewFolder, enabled = !state.loading && state.error == null) {
|
||||
Icon(Icons.Filled.CreateNewFolder, contentDescription = stringResource(R.string.folder_new))
|
||||
}
|
||||
}
|
||||
},
|
||||
navigationIcon = {
|
||||
IconButton(onClick = if (state.parent != null) onUp else onDismiss) {
|
||||
Icon(
|
||||
if (state.parent != null) Icons.AutoMirrored.Filled.ArrowBack else Icons.Filled.Close,
|
||||
contentDescription = stringResource(if (state.parent != null) R.string.back else R.string.close),
|
||||
)
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
state.path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
Button(
|
||||
onClick = onPick,
|
||||
enabled = !state.loading && state.error == null,
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp).heightIn(min = 48.dp),
|
||||
) { Text(confirm) }
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when {
|
||||
state.error != null -> Text(state.error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
|
||||
state.loading && state.folders.isEmpty() -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
|
||||
state.folders.isEmpty() -> Text(
|
||||
stringResource(R.string.files_no_folders),
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.align(Alignment.Center).padding(32.dp),
|
||||
)
|
||||
|
||||
else -> LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.folders, key = { it.path }) { folder ->
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth().clickable { onOpen(folder.path) },
|
||||
leadingContent = {
|
||||
Icon(
|
||||
if (folder.kind == "mount") Icons.Filled.FolderShared else Icons.Filled.Folder,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
headlineContent = { Text(folder.name.ifBlank { folder.path }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The trash as the page draws it. */
|
||||
data class TrashState(val items: List<TrashItem> = emptyList(), val loading: Boolean = true, val error: String? = null)
|
||||
|
||||
/** What the trash page can do; nothing by default, for the screenshot tests. */
|
||||
interface TrashActions {
|
||||
fun restore(item: TrashItem) {}
|
||||
|
||||
fun remove(item: TrashItem) {}
|
||||
|
||||
fun empty() {}
|
||||
|
||||
fun close() {}
|
||||
}
|
||||
|
||||
/** The trash: what was deleted, each to be restored or removed for good, and all of it emptied. [onChanged]: something went back to the tree. */
|
||||
@Composable
|
||||
fun TrashDialog(onClose: () -> Unit, onChanged: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember { mutableStateOf(TrashState()) }
|
||||
var asking by remember { mutableStateOf<TrashItem?>(null) }
|
||||
var emptying by remember { mutableStateOf(false) }
|
||||
var said by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
fun act(block: suspend (ApiClient) -> List<TrashItem>) {
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
state = TrashState(block(api), loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
val words = context.filesSay(e)
|
||||
if (state.loading) state = state.copy(loading = false, error = words) else said = words
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) { act { it.trash().items } }
|
||||
val actions = remember {
|
||||
object : TrashActions {
|
||||
override fun restore(item: TrashItem) = act { api ->
|
||||
api.restoreTrashed(item.id).items.also { onChanged() }
|
||||
}
|
||||
|
||||
override fun remove(item: TrashItem) {
|
||||
asking = item
|
||||
}
|
||||
|
||||
override fun empty() {
|
||||
emptying = true
|
||||
}
|
||||
|
||||
override fun close() = onClose()
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
TrashContent(state, actions)
|
||||
}
|
||||
asking?.let { item ->
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.trash_remove_confirm, item.name),
|
||||
stringResource(R.string.trash_remove),
|
||||
onConfirm = {
|
||||
asking = null
|
||||
act { it.removeTrashed(item.id).items }
|
||||
},
|
||||
onDismiss = { asking = null },
|
||||
)
|
||||
}
|
||||
if (emptying) {
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.trash_empty_confirm),
|
||||
stringResource(R.string.trash_empty),
|
||||
onConfirm = {
|
||||
emptying = false
|
||||
act { it.removeTrashed().items }
|
||||
},
|
||||
onDismiss = { emptying = false },
|
||||
)
|
||||
}
|
||||
said?.let { SaidDialog(it, onClose = { said = null }) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The trash's page. A row is the thing's name over where it was, and two buttons of 48 dp at
|
||||
* its end: the name gives, the buttons keep their size.
|
||||
*/
|
||||
@Composable
|
||||
fun TrashContent(state: TrashState, actions: TrashActions) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = actions::close) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = { Text(stringResource(R.string.trash), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
actions = {
|
||||
IconButton(onClick = actions::empty, enabled = state.items.isNotEmpty()) {
|
||||
Icon(Icons.Filled.DeleteSweep, contentDescription = stringResource(R.string.trash_empty))
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when {
|
||||
state.error != null -> Text(state.error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
|
||||
state.loading -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
|
||||
state.items.isEmpty() -> Text(
|
||||
stringResource(R.string.trash_is_empty),
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.align(Alignment.Center).padding(32.dp),
|
||||
)
|
||||
|
||||
else -> LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.items, key = { it.id }) { item ->
|
||||
ListItem(
|
||||
leadingContent = { EntryIcon(if (item.kind == "file") null else item.kind, null, selected = false) },
|
||||
headlineContent = { Text(item.name.ifBlank { item.path }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = {
|
||||
val size = if (item.kind == "file") Formatter.formatShortFileSize(context, item.size) else null
|
||||
Text(listOfNotNull(FileKinds.parent(item.path), size).joinToString(" · "), maxLines = 1, overflow = TextOverflow.StartEllipsis)
|
||||
},
|
||||
trailingContent = {
|
||||
Row {
|
||||
IconButton(onClick = { actions.restore(item) }) {
|
||||
Icon(Icons.Filled.RestoreFromTrash, contentDescription = stringResource(R.string.restore))
|
||||
}
|
||||
IconButton(onClick = { actions.remove(item) }) {
|
||||
Icon(Icons.Filled.DeleteForever, contentDescription = stringResource(R.string.trash_remove), tint = palette.danger)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A file's versions as the page draws them. */
|
||||
data class VersionsState(val versions: List<FileVersion> = emptyList(), val loading: Boolean = true, val error: String? = null)
|
||||
|
||||
/** A file's versions, newest first; an older one can be made the file again, which adds a version and loses none. */
|
||||
@Composable
|
||||
fun VersionsDialog(path: String, onClose: () -> Unit, onRestored: () -> Unit, onDownload: ((FileVersion) -> Unit)? = null) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember(path) { mutableStateOf(VersionsState()) }
|
||||
var asking by remember { mutableStateOf<FileVersion?>(null) }
|
||||
LaunchedEffect(path) {
|
||||
state = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
VersionsState(api.fileVersions(path).versions, loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
VersionsState(loading = false, error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
VersionsContent(FileKinds.name(path), state, onRestore = { asking = it }, onClose = onClose, onDownload = onDownload)
|
||||
}
|
||||
asking?.let { version ->
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.version_restore_confirm),
|
||||
stringResource(R.string.version_restore),
|
||||
onConfirm = {
|
||||
asking = null
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
api.restoreVersion(path, version.id)
|
||||
onRestored()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state = state.copy(error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
},
|
||||
onDismiss = { asking = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The versions' page: when, by whom and how large; the one the file holds now says so, the others
|
||||
* can be restored, and any of them saved to the phone as it was ([onDownload]; a 48 dp button
|
||||
* before the row's last part, so the buttons stand in one column whatever that part says).
|
||||
*/
|
||||
@Composable
|
||||
fun VersionsContent(
|
||||
name: String,
|
||||
state: VersionsState,
|
||||
onRestore: (FileVersion) -> Unit = {},
|
||||
onClose: () -> Unit = {},
|
||||
onDownload: ((FileVersion) -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = {
|
||||
Column {
|
||||
Text(stringResource(R.string.versions), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(name, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
state.error?.let { Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) }
|
||||
if (state.loading) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
|
||||
return@Column
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.versions, key = { it.id }) { version ->
|
||||
val download: (@Composable () -> Unit)? = if (onDownload != null) {
|
||||
{
|
||||
IconButton(onClick = { onDownload(version) }) {
|
||||
Icon(Icons.Filled.Download, contentDescription = stringResource(R.string.download))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
ListItem(
|
||||
headlineContent = { Text(ScheduleLogic.moment(version.at) ?: version.id, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = {
|
||||
val facts = listOfNotNull(version.by?.ifBlank { null }, Formatter.formatShortFileSize(context, version.size))
|
||||
Text(facts.joinToString(" · "), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
},
|
||||
leadingContent = download,
|
||||
trailingContent = {
|
||||
if (version.current) {
|
||||
Text(stringResource(R.string.version_current), style = MaterialTheme.typography.labelLarge, color = palette.inkMuted)
|
||||
} else {
|
||||
TextButton(onClick = { onRestore(version) }) { Text(stringResource(R.string.restore)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,59 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class, androidx.compose.foundation.ExperimentalFoundationApi::class)
|
||||
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.app.Application
|
||||
import android.net.Uri
|
||||
import android.text.format.Formatter
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Archive
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Code
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.DriveFileMove
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.FolderShared
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Movie
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material.icons.filled.PictureAsPdf
|
||||
import androidx.compose.material.icons.filled.RestoreFromTrash
|
||||
import androidx.compose.material.icons.filled.SelectAll
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.TableChart
|
||||
import androidx.compose.material3.BottomAppBar
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.ListItemDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
@@ -31,10 +63,12 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
@@ -45,34 +79,136 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.BatchAnswer
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileExists
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileListing
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.TreeFileViewer
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** One directory of the person's tree, and whether it is on its way. */
|
||||
/**
|
||||
* One directory of the person's tree: what is in it, what is chosen in it, and what is under
|
||||
* way. [error] is a listing that could not be read (said above the list, which stays); [said] a
|
||||
* refusal of something the person did (a sentence to read, in a dialog); [notice] a word that
|
||||
* it was done.
|
||||
*/
|
||||
data class FilesState(
|
||||
val path: String = "/",
|
||||
val parent: String? = null,
|
||||
val entries: List<FileEntry> = emptyList(),
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
)
|
||||
val selected: Set<String> = emptySet(),
|
||||
/** An upload under way: which file of how many, and how far it is. */
|
||||
val upload: Transfer? = null,
|
||||
/** A write under way (a move, a rename…): the list waits for it. */
|
||||
val working: Boolean = false,
|
||||
val said: String? = null,
|
||||
val notice: String? = null,
|
||||
) {
|
||||
val selecting: Boolean get() = selected.isNotEmpty()
|
||||
|
||||
/** The chosen entries, in the list's order. */
|
||||
val chosen: List<FileEntry> get() = entries.filter { it.path in selected }
|
||||
|
||||
fun toggled(path: String): FilesState = copy(selected = if (path in selected) selected - path else selected + path)
|
||||
|
||||
fun allSelected(): FilesState = copy(selected = entries.map { it.path }.toSet())
|
||||
|
||||
/** A listing read: the directory it is of, and of what was chosen only what is still there. */
|
||||
fun listed(listing: FileListing): FilesState {
|
||||
val same = listing.path == path
|
||||
val there = listing.entries.map { it.path }.toSet()
|
||||
return copy(
|
||||
path = listing.path,
|
||||
parent = listing.parent,
|
||||
entries = listing.entries,
|
||||
loading = false,
|
||||
error = null,
|
||||
selected = if (same) selected intersect there else emptySet(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** What a batch ended in: the server's sentences for what it refused, and the word for what it did. */
|
||||
data class BatchOutcome(val said: String?, val done: Int)
|
||||
|
||||
fun outcome(answer: BatchAnswer): BatchOutcome {
|
||||
if (answer.failed == 0) return BatchOutcome(null, answer.done)
|
||||
// Where the server gave no sentence, at least which ones: their names.
|
||||
val names = answer.results.filter { !it.ok }.take(3).joinToString(", ") { FileKinds.name(it.path) }
|
||||
return BatchOutcome(answer.refusals().joinToString("\n").ifBlank { names }, answer.done)
|
||||
}
|
||||
|
||||
/** Something the Files page asks the person before it is done, or a page it opens over itself. */
|
||||
sealed interface Ask {
|
||||
data object NewFolder : Ask
|
||||
|
||||
data object NewFile : Ask
|
||||
|
||||
data object Trash : Ask
|
||||
|
||||
data class Rename(val entry: FileEntry) : Ask
|
||||
|
||||
data class Delete(val entries: List<FileEntry>) : Ask
|
||||
|
||||
data class Move(val entries: List<FileEntry>) : Ask
|
||||
|
||||
data class Copy(val entries: List<FileEntry>) : Ask
|
||||
|
||||
data class Versions(val entry: FileEntry) : Ask
|
||||
}
|
||||
|
||||
/** What the Files page can do; nothing by default, for the screenshot tests. */
|
||||
interface FilesActions {
|
||||
fun back() {}
|
||||
|
||||
fun open(entry: FileEntry) {}
|
||||
|
||||
fun reload() {}
|
||||
|
||||
fun toggle(entry: FileEntry) {}
|
||||
|
||||
fun selectAll() {}
|
||||
|
||||
fun clearSelection() {}
|
||||
|
||||
fun pickUpload() {}
|
||||
|
||||
fun ask(what: Ask) {}
|
||||
|
||||
fun download(entries: List<FileEntry>) {}
|
||||
|
||||
fun share(entries: List<FileEntry>) {}
|
||||
|
||||
fun openWith(entry: FileEntry) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The person's files, read-only: `GET /api/v2/files` as the explorer's listing. The tree is read
|
||||
* as the person, with no chat -- their own access, the same the web UI's explorer draws by.
|
||||
* The person's files as a file manager: `GET /api/v2/files` and the explorer's writes. The tree
|
||||
* is read and changed as the person, with no chat -- their own access, the same the web UI's
|
||||
* explorer draws by -- and every refusal is the server's own sentence.
|
||||
*/
|
||||
class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(FilesState(loading = true))
|
||||
val state = _state.asStateFlow()
|
||||
private var loading: Job? = null
|
||||
private var uploading: Job? = null
|
||||
private val app: Application get() = getApplication()
|
||||
|
||||
private suspend fun api(): ApiClient = app.lembas.instances.client() ?: throw ApiException(401, app.getString(R.string.assist_signed_out))
|
||||
|
||||
/**
|
||||
* Opens a directory. A refusal (a path no longer readable, the server unreachable) keeps the
|
||||
@@ -83,16 +219,14 @@ class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
loading = viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client()
|
||||
if (api == null) {
|
||||
_state.update { it.copy(loading = false) }
|
||||
return@launch
|
||||
}
|
||||
val listing = api.files(path)
|
||||
_state.value = FilesState(path = listing.path, parent = listing.parent, entries = listing.entries)
|
||||
// Also read again after an upload that ended behind the lock: not before the app is in front.
|
||||
app.lembas.gate.pass()
|
||||
val listing = api().files(path)
|
||||
_state.update { it.listed(listing) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
if (e is kotlinx.coroutines.CancellationException) throw e
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
_state.update { it.copy(loading = false, error = app.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,85 +238,464 @@ class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
open(parent)
|
||||
return true
|
||||
}
|
||||
|
||||
fun toggle(entry: FileEntry) = _state.update { it.toggled(entry.path) }
|
||||
|
||||
fun selectAll() = _state.update { it.allSelected() }
|
||||
|
||||
fun clearSelection() = _state.update { it.copy(selected = emptySet()) }
|
||||
|
||||
fun clearSaid() = _state.update { it.copy(said = null, notice = null) }
|
||||
|
||||
/** One write, then the directory read again: what is there is what the server says is there. */
|
||||
private fun write(block: suspend (ApiClient) -> String?) {
|
||||
if (_state.value.working) return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(working = true, said = null, notice = null) }
|
||||
try {
|
||||
val notice = block(api())
|
||||
_state.update { it.copy(notice = notice) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(said = app.filesSay(e)) }
|
||||
} finally {
|
||||
_state.update { it.copy(working = false) }
|
||||
}
|
||||
reload()
|
||||
}
|
||||
}
|
||||
|
||||
fun newFolder(name: String) = write { api ->
|
||||
api.makeFolder(_state.value.path, name)
|
||||
null
|
||||
}
|
||||
|
||||
/**
|
||||
* A new, empty text file, and [then] its path, to open it for writing. The instance makes it
|
||||
* only where nothing is called that (`create`): otherwise nothing is written and its own
|
||||
* sentence says what is there. An instance from before `create` would write over what is
|
||||
* there, so the directory is read first and a name it holds is refused here
|
||||
* ([ApiClient.newFile]).
|
||||
*/
|
||||
fun newFile(name: String, then: (String) -> Unit) = write { api ->
|
||||
try {
|
||||
then(api.newFile(_state.value.path, name))
|
||||
} catch (e: FileExists) {
|
||||
_state.update { it.copy(said = e.message?.ifBlank { null } ?: app.getString(R.string.files_taken, name)) }
|
||||
}
|
||||
null
|
||||
}
|
||||
|
||||
fun rename(entry: FileEntry, name: String) = write { api ->
|
||||
api.renameFile(entry.path, name)
|
||||
null
|
||||
}
|
||||
|
||||
/** Move or copy the entries into the directory [to], or with `delete` put them in the trash; each is answered for by itself. */
|
||||
fun batch(op: String, entries: List<FileEntry>, to: String? = null) = write { api ->
|
||||
val done = outcome(api.batchFiles(op, entries.map { it.path }, to))
|
||||
_state.update { it.copy(selected = emptySet(), said = done.said) }
|
||||
when {
|
||||
done.done == 0 -> null
|
||||
op == "delete" -> app.getString(R.string.files_trashed)
|
||||
op == "copy" -> app.getString(R.string.copied)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload files of the phone into the directory shown, one request each: a file the instance
|
||||
* refuses (too large: its 413 names the file) does not take the others with it. Each is
|
||||
* streamed from where it is; none is read into memory.
|
||||
*/
|
||||
fun upload(uris: List<Uri>) {
|
||||
if (uris.isEmpty() || uploading?.isActive == true) return
|
||||
val dir = _state.value.path
|
||||
uploading = viewModelScope.launch {
|
||||
val refused = mutableListOf<String>()
|
||||
var sent = 0
|
||||
try {
|
||||
val api = api()
|
||||
val files = uris.map { app.contentResolver.describe(it) }
|
||||
files.forEachIndexed { i, file ->
|
||||
val words = app.getString(R.string.files_uploading, (i + 1).toString(), files.size.toString())
|
||||
_state.update { it.copy(upload = Transfer(words, 0, file.size)) }
|
||||
var last = 0L
|
||||
try {
|
||||
// The file under way when the phone locks goes through; the next waits for the app in front, unlocked.
|
||||
app.lembas.gate.pass { waiting -> _state.update { it.copy(upload = it.upload?.copy(waiting = waiting)) } }
|
||||
api.uploadFrom(app, file, dir) { bytes ->
|
||||
if (bytes - last >= 256 * 1024) {
|
||||
last = bytes
|
||||
_state.update { it.copy(upload = it.upload?.copy(done = bytes)) }
|
||||
}
|
||||
}
|
||||
sent++
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
refused += app.filesSay(e)
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
refused += app.filesSay(e)
|
||||
} finally {
|
||||
val words = refused.distinct().take(3).joinToString("\n").ifBlank { null }
|
||||
_state.update { it.copy(upload = null, said = words, notice = if (sent > 0) app.getString(R.string.files_uploaded) else null) }
|
||||
reload()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun cancelUpload() {
|
||||
uploading?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun FilesScreen(onBack: () -> Unit, model: FilesViewModel = viewModel()) {
|
||||
fun FilesScreen(onBack: () -> Unit, start: String? = null, model: FilesViewModel = viewModel(), transfers: TransferViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
var viewing by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
LaunchedEffect(Unit) { if (state.entries.isEmpty() && state.error == null) model.open(state.path) }
|
||||
var writing by rememberSaveable { mutableStateOf(false) }
|
||||
var asked by remember { mutableStateOf<Ask?>(null) }
|
||||
var saving by remember { mutableStateOf<List<FileEntry>>(emptyList()) }
|
||||
// Opened at a folder ([start]: where a generated file is) the first time; after that, where the person walked to.
|
||||
LaunchedEffect(Unit) { if (state.entries.isEmpty() && state.error == null) model.open(start?.ifBlank { null } ?: state.path) }
|
||||
val saveVersion = rememberSaver(transfers)
|
||||
LaunchedEffect(state.notice) {
|
||||
state.notice?.let {
|
||||
Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
|
||||
model.clearSaid()
|
||||
}
|
||||
}
|
||||
|
||||
// Back goes up one directory first, as a file manager's does; at the top it leaves.
|
||||
BackHandler(enabled = state.parent != null) { model.up() }
|
||||
// Back lets go of what is chosen first, then goes up one directory, as a file manager's does; at the top it leaves.
|
||||
BackHandler(enabled = state.selecting || state.parent != null) { if (state.selecting) model.clearSelection() else model.up() }
|
||||
|
||||
val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { model.upload(it) }
|
||||
val saveTo = rememberLauncherForActivityResult(CreateFile()) { to ->
|
||||
val what = saving
|
||||
saving = emptyList()
|
||||
if (to != null && what.isNotEmpty()) {
|
||||
transfers.download(what.map { it.path }, zip = asZip(what), to = to)
|
||||
model.clearSelection()
|
||||
}
|
||||
}
|
||||
val actions = remember(model, transfers) {
|
||||
object : FilesActions {
|
||||
override fun back() {
|
||||
if (!model.up()) onBack()
|
||||
}
|
||||
|
||||
override fun open(entry: FileEntry) {
|
||||
if (entry.isFolder) {
|
||||
model.open(entry.path)
|
||||
} else {
|
||||
writing = false
|
||||
viewing = entry.path
|
||||
}
|
||||
}
|
||||
|
||||
override fun reload() = model.reload()
|
||||
|
||||
override fun toggle(entry: FileEntry) = model.toggle(entry)
|
||||
|
||||
override fun selectAll() = model.selectAll()
|
||||
|
||||
override fun clearSelection() = model.clearSelection()
|
||||
|
||||
override fun pickUpload() = pick.launch(arrayOf("*/*"))
|
||||
|
||||
override fun ask(what: Ask) {
|
||||
asked = what
|
||||
}
|
||||
|
||||
override fun download(entries: List<FileEntry>) {
|
||||
if (entries.isEmpty()) return
|
||||
saving = entries
|
||||
val zip = asZip(entries)
|
||||
saveTo.launch(
|
||||
CreateFile.Ask(
|
||||
if (zip) {
|
||||
TransferViewModel.zipName(
|
||||
entries.map {
|
||||
it.path
|
||||
},
|
||||
)
|
||||
} else {
|
||||
entries[0].name
|
||||
},
|
||||
if (zip) "application/zip" else entries[0].mime,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
override fun share(entries: List<FileEntry>) {
|
||||
transfers.share(entries)
|
||||
model.clearSelection()
|
||||
}
|
||||
|
||||
override fun openWith(entry: FileEntry) = transfers.openWith(entry.path, entry.name)
|
||||
}
|
||||
}
|
||||
|
||||
FilesContent(state, actions)
|
||||
|
||||
when (val now = asked) {
|
||||
null -> Unit
|
||||
|
||||
Ask.NewFolder -> NameDialog(
|
||||
stringResource(R.string.folder_new),
|
||||
stringResource(R.string.files_new_folder_ask),
|
||||
"",
|
||||
stringResource(R.string.save),
|
||||
onName = {
|
||||
asked = null
|
||||
model.newFolder(it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
Ask.NewFile -> NameDialog(
|
||||
stringResource(R.string.files_new_file),
|
||||
stringResource(R.string.files_new_file_ask),
|
||||
"",
|
||||
stringResource(R.string.save),
|
||||
onName = { name ->
|
||||
asked = null
|
||||
model.newFile(name) { path ->
|
||||
writing = true
|
||||
viewing = path
|
||||
}
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Rename -> NameDialog(
|
||||
stringResource(R.string.rename),
|
||||
stringResource(R.string.files_new_name),
|
||||
now.entry.name,
|
||||
stringResource(R.string.rename),
|
||||
onName = {
|
||||
asked = null
|
||||
model.rename(now.entry, it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Delete -> ConfirmDialog(
|
||||
if (now.entries.size == 1) {
|
||||
stringResource(R.string.files_trash_one, now.entries[0].name)
|
||||
} else {
|
||||
stringResource(R.string.files_trash_many, now.entries.size.toString())
|
||||
},
|
||||
stringResource(R.string.files_to_trash),
|
||||
onConfirm = {
|
||||
asked = null
|
||||
model.batch("delete", now.entries)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Move -> FolderPicker(
|
||||
stringResource(R.string.files_move_which),
|
||||
stringResource(R.string.files_move_here),
|
||||
state.path,
|
||||
onPick = {
|
||||
asked = null
|
||||
model.batch("move", now.entries, it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
hidden = now.entries.map { it.path }.toSet(),
|
||||
)
|
||||
|
||||
is Ask.Copy -> FolderPicker(
|
||||
stringResource(R.string.files_copy_which),
|
||||
stringResource(R.string.files_copy_here),
|
||||
state.path,
|
||||
onPick = {
|
||||
asked = null
|
||||
model.batch("copy", now.entries, it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Versions -> VersionsDialog(
|
||||
now.entry.path,
|
||||
onDownload = { version -> saveVersion(Raw.Path(now.entry.path, version.id), now.entry.name, now.entry.mime) },
|
||||
onClose = { asked = null },
|
||||
onRestored = {
|
||||
asked = null
|
||||
model.reload()
|
||||
},
|
||||
)
|
||||
|
||||
Ask.Trash -> TrashDialog(onClose = { asked = null }, onChanged = model::reload)
|
||||
}
|
||||
|
||||
state.upload?.let { TransferDialog(it, onCancel = model::cancelUpload) }
|
||||
state.said?.let { SaidDialog(it, onClose = model::clearSaid) }
|
||||
TransferHost(transfers)
|
||||
viewing?.let { path -> TreeFileViewer(path, onClose = { viewing = null }, startEditing = writing, onChanged = model::reload) }
|
||||
}
|
||||
|
||||
/** Several things, or a folder, leave as one zip; a single file as itself. */
|
||||
fun asZip(entries: List<FileEntry>): Boolean = entries.size > 1 || entries.any { it.isFolder }
|
||||
|
||||
/**
|
||||
* The Files page, from [state] alone. A tap opens; a long press chooses, and while anything is
|
||||
* chosen a tap chooses too and the bar at the bottom acts on all of it. Each row's own menu
|
||||
* (the three dots, 48 dp) has what can be done to that one thing.
|
||||
*/
|
||||
@Composable
|
||||
fun FilesContent(state: FilesState, actions: FilesActions) {
|
||||
val palette = LocalPalette.current
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = { if (!model.up()) onBack() }) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
if (state.selecting) {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = actions::clearSelection) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.cancel)) }
|
||||
},
|
||||
title = { Text(stringResource(R.string.files_selected, state.selected.size.toString()), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
actions = {
|
||||
IconButton(onClick = actions::selectAll) {
|
||||
Icon(Icons.Filled.SelectAll, contentDescription = stringResource(R.string.files_select_all))
|
||||
}
|
||||
},
|
||||
)
|
||||
} else {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = actions::back) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
Text(stringResource(R.string.files), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
if (state.parent == null) stringResource(R.string.files_all) else state.path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = if (state.parent == null) null else FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
Box {
|
||||
IconButton(onClick = { adding = true }) { Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.files_upload)) }
|
||||
DropdownMenu(expanded = adding, onDismissRequest = { adding = false }) {
|
||||
MenuItem(R.string.files_upload) {
|
||||
adding = false
|
||||
actions.pickUpload()
|
||||
}
|
||||
MenuItem(R.string.folder_new) {
|
||||
adding = false
|
||||
actions.ask(Ask.NewFolder)
|
||||
}
|
||||
MenuItem(R.string.files_new_file) {
|
||||
adding = false
|
||||
actions.ask(Ask.NewFile)
|
||||
}
|
||||
}
|
||||
}
|
||||
IconButton(onClick = {
|
||||
actions.ask(Ask.Trash)
|
||||
}) { Icon(Icons.Filled.RestoreFromTrash, contentDescription = stringResource(R.string.trash)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
if (state.selecting) {
|
||||
val chosen = state.chosen
|
||||
// Five actions of one size, spread evenly: none of them is a word, so none can crowd another.
|
||||
BottomAppBar {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) {
|
||||
BarButton(Icons.Filled.DriveFileMove, R.string.files_move) { actions.ask(Ask.Move(chosen)) }
|
||||
BarButton(Icons.Filled.ContentCopy, R.string.files_copy_to) { actions.ask(Ask.Copy(chosen)) }
|
||||
BarButton(Icons.Filled.Download, if (asZip(chosen)) R.string.files_download_zip else R.string.download) { actions.download(chosen) }
|
||||
BarButton(Icons.Filled.Share, R.string.report_share) { actions.share(chosen) }
|
||||
BarButton(Icons.Filled.Delete, R.string.files_to_trash) { actions.ask(Ask.Delete(chosen)) }
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
Text(stringResource(R.string.files), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
if (state.parent == null) stringResource(R.string.files_all) else state.path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = if (state.parent == null) null else FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
state.error?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
}
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = { model.reload() }, modifier = Modifier.fillMaxSize()) {
|
||||
if (state.working) LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp))
|
||||
state.error?.let { Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) }
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = actions::reload, modifier = Modifier.fillMaxSize()) {
|
||||
if (state.entries.isEmpty() && !state.loading && state.error == null) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
stringResource(R.string.files_empty),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(32.dp),
|
||||
)
|
||||
Text(stringResource(R.string.files_empty), color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(32.dp))
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.entries, key = { it.path }) { entry ->
|
||||
EntryRow(entry) { if (entry.isFolder) model.open(entry.path) else viewing = entry.path }
|
||||
EntryRow(entry, selected = entry.path in state.selected, selecting = state.selecting, actions = actions)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
viewing?.let { path -> TreeFileViewer(path, onClose = { viewing = null }) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryRow(entry: FileEntry, onOpen: () -> Unit) {
|
||||
private fun MenuItem(label: Int, onClick: () -> Unit) = DropdownMenuItem(text = { Text(stringResource(label)) }, onClick = onClick)
|
||||
|
||||
@Composable
|
||||
private fun BarButton(icon: ImageVector, label: Int, onClick: () -> Unit) {
|
||||
IconButton(onClick = onClick) { Icon(icon, contentDescription = stringResource(label)) }
|
||||
}
|
||||
|
||||
/** What an entry is, as a picture: a folder, a shared folder, or the file's kind; a tick when it is chosen. */
|
||||
@Composable
|
||||
internal fun EntryIcon(folder: String?, fileKind: String?, selected: Boolean) {
|
||||
val palette = LocalPalette.current
|
||||
val icon = when {
|
||||
selected -> Icons.Filled.CheckCircle
|
||||
|
||||
folder == "mount" -> Icons.Filled.FolderShared
|
||||
|
||||
folder != null -> Icons.Filled.Folder
|
||||
|
||||
else -> when (fileKind) {
|
||||
"image", "svg" -> Icons.Filled.Image
|
||||
"pdf" -> Icons.Filled.PictureAsPdf
|
||||
"audio" -> Icons.Filled.MusicNote
|
||||
"video" -> Icons.Filled.Movie
|
||||
"table" -> Icons.Filled.TableChart
|
||||
"code", "html", "notebook" -> Icons.Filled.Code
|
||||
"archive" -> Icons.Filled.Archive
|
||||
"model3d", "binary" -> Icons.AutoMirrored.Filled.InsertDriveFile
|
||||
else -> Icons.Filled.Description
|
||||
}
|
||||
}
|
||||
Icon(icon, contentDescription = null, tint = if (selected) palette.accent else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryRow(entry: FileEntry, selected: Boolean, selecting: Boolean, actions: FilesActions) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen),
|
||||
leadingContent = {
|
||||
Icon(
|
||||
when (entry.kind) {
|
||||
"mount" -> Icons.Filled.FolderShared
|
||||
"dir" -> Icons.Filled.Folder
|
||||
else -> Icons.Filled.Description
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.combinedClickable(
|
||||
onClick = { if (selecting) actions.toggle(entry) else actions.open(entry) },
|
||||
onLongClick = { actions.toggle(entry) },
|
||||
),
|
||||
colors = ListItemDefaults.colors(containerColor = if (selected) palette.accentSoft else palette.bg),
|
||||
leadingContent = { EntryIcon(if (entry.isFolder) entry.kind else null, entry.fileKind, selected) },
|
||||
headlineContent = { Text(entry.name.ifBlank { entry.path }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = if (entry.isFolder) {
|
||||
null
|
||||
@@ -192,5 +705,33 @@ private fun EntryRow(entry: FileEntry, onOpen: () -> Unit) {
|
||||
Text(line, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
},
|
||||
trailingContent = if (selecting) {
|
||||
null
|
||||
} else {
|
||||
{
|
||||
Box {
|
||||
IconButton(onClick = { menu = true }) { Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more)) }
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
val one = listOf(entry)
|
||||
val then: (() -> Unit) -> (() -> Unit) = { act ->
|
||||
{
|
||||
menu = false
|
||||
act()
|
||||
}
|
||||
}
|
||||
MenuItem(R.string.rename, then { actions.ask(Ask.Rename(entry)) })
|
||||
MenuItem(R.string.files_move, then { actions.ask(Ask.Move(one)) })
|
||||
MenuItem(R.string.files_copy_to, then { actions.ask(Ask.Copy(one)) })
|
||||
MenuItem(if (entry.isFolder) R.string.files_download_zip else R.string.download, then { actions.download(one) })
|
||||
MenuItem(R.string.report_share, then { actions.share(one) })
|
||||
if (!entry.isFolder) {
|
||||
MenuItem(R.string.files_open_with, then { actions.openWith(entry) })
|
||||
MenuItem(R.string.versions, then { actions.ask(Ask.Versions(entry)) })
|
||||
}
|
||||
MenuItem(R.string.files_to_trash, then { actions.ask(Ask.Delete(one)) })
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.app.Application
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.text.format.Formatter
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.share.SharedRefused
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Something on its way to or from the instance: what it is, and how far ([total] -1: not known).
|
||||
* [waiting]: its next request has not started, because the app is not in front or the phone is
|
||||
* locked ([eu.llembas.android.InstanceGate]); it goes on by itself.
|
||||
*/
|
||||
data class Transfer(val text: String, val done: Long = 0, val total: Long = -1, val waiting: Boolean = false)
|
||||
|
||||
/** A transfer under way, what it ended in, and the other app to open once a copy is ready. */
|
||||
data class TransferState(val running: Transfer? = null, val error: String? = null, val notice: String? = null, val launch: Intent? = null)
|
||||
|
||||
/** A failure of the file manager in words: an instance without these routes says so, the rest as everywhere. */
|
||||
fun Context.filesSay(e: Throwable): String = when {
|
||||
noSuchRoute(e) -> getString(R.string.viewer_unavailable)
|
||||
e is SharedRefused -> getString(R.string.share_refused)
|
||||
e is ApiException && e.message.isNullOrBlank() -> getString(R.string.files_not_shown)
|
||||
else -> explain(e)
|
||||
}
|
||||
|
||||
/**
|
||||
* Files leaving the instance for the phone: a download into a document the person chose, and a
|
||||
* copy in the private cache for another app (Open with, Share). One at a time, with its
|
||||
* progress, and it can be given up. It outlives a turn of the phone. Each request asks the gate
|
||||
* first ([turn]): none starts while the phone is locked or the app is not in front, and the one
|
||||
* under way then is let finish.
|
||||
*/
|
||||
class TransferViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(TransferState())
|
||||
val state = _state.asStateFlow()
|
||||
private var job: Job? = null
|
||||
private val app: Application get() = getApplication()
|
||||
|
||||
/** One file's bytes, or with [zip] several files and folders as one zip, into the document [to]. */
|
||||
fun download(paths: List<String>, zip: Boolean, to: Uri) = start { api, progress ->
|
||||
turn()
|
||||
api.downloadTo(app, if (zip) api.zipFiles(paths) else api.rawFile(paths.first()), to, progress)
|
||||
_state.update { it.copy(notice = app.getString(R.string.files_downloaded)) }
|
||||
}
|
||||
|
||||
/** One thing's bytes -- a version of a file, a generated file by its id, an attachment -- into the document [to]. */
|
||||
fun download(what: Raw, to: Uri) = start { api, progress ->
|
||||
turn()
|
||||
api.downloadTo(app, api.raw(what), to, progress)
|
||||
_state.update { it.copy(notice = app.getString(R.string.files_downloaded)) }
|
||||
}
|
||||
|
||||
fun openWith(path: String, name: String) = openWith(Raw.Path(path), name)
|
||||
|
||||
/** A copy for another app to open; its type is read from the copy ([Handover.view]), not taken from the instance. */
|
||||
fun openWith(what: Raw, name: String) = start { api, progress ->
|
||||
FileCache.sweepShared(app)
|
||||
turn()
|
||||
val copy = api.copyInto(api.raw(what), FileCache.shared(app, name), progress = progress)
|
||||
_state.update { it.copy(launch = Handover.view(app, copy)) }
|
||||
}
|
||||
|
||||
/** One thing that is not named by a path (a generated file by its id), shared as itself. */
|
||||
fun share(what: Raw, name: String, mime: String) = start { api, progress ->
|
||||
FileCache.sweepShared(app)
|
||||
turn()
|
||||
val copy = api.copyInto(api.raw(what), FileCache.shared(app, name), progress = progress)
|
||||
_state.update { it.copy(launch = Handover.share(app, listOf(copy), mime.ifBlank { "*/*" })) }
|
||||
}
|
||||
|
||||
/** A few files go as themselves; many, or any folder, as one zip the instance makes. */
|
||||
fun share(entries: List<FileEntry>) = start { api, progress ->
|
||||
if (entries.isEmpty()) return@start
|
||||
FileCache.sweepShared(app)
|
||||
val plain = entries.none { it.isFolder } && entries.size <= SHARE_MOST
|
||||
val copies = if (plain) {
|
||||
entries.map {
|
||||
turn()
|
||||
api.copyInto(api.rawFile(it.path), FileCache.shared(app, it.name), progress = progress)
|
||||
}
|
||||
} else {
|
||||
turn()
|
||||
listOf(api.copyInto(api.zipFiles(entries.map { it.path }), FileCache.shared(app, zipName(entries.map { it.path })), progress = progress))
|
||||
}
|
||||
val mime = if (plain) entries.map { it.mime }.distinct().singleOrNull()?.ifBlank { null } ?: "*/*" else "application/zip"
|
||||
_state.update { it.copy(launch = Handover.share(app, copies, mime)) }
|
||||
}
|
||||
|
||||
fun launched() = _state.update { it.copy(launch = null) }
|
||||
|
||||
fun say(error: String) = _state.update { it.copy(error = error) }
|
||||
|
||||
fun clear() = _state.update { it.copy(error = null, notice = null) }
|
||||
|
||||
fun cancel() {
|
||||
job?.cancel()
|
||||
}
|
||||
|
||||
/** The gate, before a request: while it is shut the dialog says the transfer is waiting. */
|
||||
private suspend fun turn() = app.lembas.gate.pass { waiting -> _state.update { it.copy(running = it.running?.copy(waiting = waiting)) } }
|
||||
|
||||
private fun start(block: suspend (ApiClient, (Long, Long) -> Unit) -> Unit) {
|
||||
if (job?.isActive == true) return
|
||||
job = viewModelScope.launch {
|
||||
_state.update { it.copy(running = Transfer(app.getString(R.string.files_downloading)), error = null, notice = null) }
|
||||
try {
|
||||
val api = app.lembas.instances.client() ?: throw ApiException(401, app.getString(R.string.assist_signed_out))
|
||||
block(api, stepped { done, total -> _state.update { it.copy(running = it.running?.copy(done = done, total = total)) } })
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = app.filesSay(e)) }
|
||||
} finally {
|
||||
_state.update { it.copy(running = null) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The copies another app was handed stay while it may be reading them: only the old ones go. */
|
||||
override fun onCleared() {
|
||||
FileCache.sweepShared(app)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** More files than this are shared as one zip. */
|
||||
const val SHARE_MOST = 10
|
||||
|
||||
/** What a zip of [paths] is called: the one thing's name, else the folder they are in. */
|
||||
fun zipName(paths: List<String>): String {
|
||||
val one = paths.singleOrNull()?.let { FileKinds.name(it) }
|
||||
val folder = paths.firstOrNull()?.let { FileKinds.name(FileKinds.parent(it)) }?.takeIf { it != "/" }
|
||||
return (one ?: folder ?: "files").removeSuffix(".zip") + ".zip"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "Save to" for one thing: the system's page for where it goes, and then the download into the
|
||||
* document chosen there. What is to be saved is kept while that page is open.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberSaver(transfers: TransferViewModel): (what: Raw, name: String, mime: String) -> Unit {
|
||||
var pending by remember { mutableStateOf<Raw?>(null) }
|
||||
val page = rememberLauncherForActivityResult(CreateFile()) { to ->
|
||||
val what = pending
|
||||
pending = null
|
||||
if (to != null && what != null) transfers.download(what, to)
|
||||
}
|
||||
return { what, name, mime ->
|
||||
pending = what
|
||||
page.launch(CreateFile.Ask(FileKinds.safeName(name), mime))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a screen shows of its transfers: the one under way with Cancel, the other app once a
|
||||
* copy is ready, a failure in a dialog (it is a sentence to read), and a short word when one
|
||||
* is done -- which names no file.
|
||||
*/
|
||||
@Composable
|
||||
fun TransferHost(model: TransferViewModel) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val context = LocalContext.current
|
||||
LaunchedEffect(state.launch) {
|
||||
val intent = state.launch ?: return@LaunchedEffect
|
||||
try {
|
||||
context.startActivity(intent)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
model.say(context.getString(R.string.files_no_app))
|
||||
}
|
||||
model.launched()
|
||||
}
|
||||
LaunchedEffect(state.notice) {
|
||||
state.notice?.let {
|
||||
Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
|
||||
model.clear()
|
||||
}
|
||||
}
|
||||
state.running?.let { TransferDialog(it, onCancel = model::cancel) }
|
||||
state.error?.let { SaidDialog(it, onClose = model::clear) }
|
||||
}
|
||||
|
||||
/** A transfer under way: what, how far, and Cancel. Drawn from [transfer] alone. */
|
||||
@Composable
|
||||
fun TransferDialog(transfer: Transfer, onCancel: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
AlertDialog(
|
||||
onDismissRequest = {},
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(transfer.text, style = MaterialTheme.typography.bodyLarge)
|
||||
if (transfer.waiting) Text(stringResource(R.string.files_waiting), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
if (transfer.total > 0) {
|
||||
LinearProgressIndicator(progress = { (transfer.done.toFloat() / transfer.total).coerceIn(0f, 1f) }, modifier = Modifier.fillMaxWidth())
|
||||
} else {
|
||||
LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
}
|
||||
if (transfer.done > 0) {
|
||||
val done = Formatter.formatShortFileSize(context, transfer.done)
|
||||
val line = if (transfer.total > 0) done + " / " + Formatter.formatShortFileSize(context, transfer.total) else done
|
||||
Text(line, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** A sentence the person has to read (a refusal, a failure), with one way on. */
|
||||
@Composable
|
||||
fun SaidDialog(text: String, onClose: () -> Unit) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onClose,
|
||||
text = { Text(text, style = MaterialTheme.typography.bodyLarge) },
|
||||
confirmButton = { TextButton(onClick = onClose) { Text(stringResource(R.string.close)) } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ClipData
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import android.provider.OpenableColumns
|
||||
import android.webkit.MimeTypeMap
|
||||
import androidx.activity.result.contract.ActivityResultContract
|
||||
import androidx.core.content.FileProvider
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileListing
|
||||
import eu.llembas.android.api.SNIFF_BYTES
|
||||
import eu.llembas.android.api.openType
|
||||
import eu.llembas.android.share.SharedSource
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.MediaType
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.RequestBody
|
||||
import okio.BufferedSink
|
||||
import okio.source
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* The copies of the account's files this phone holds for a moment, all in the app's private
|
||||
* cache and nowhere else: [viewing] for what a viewer needs as a file (a PDF's pages, a
|
||||
* picture's pixels), deleted when the viewer closes; [shared] for what another app is handed
|
||||
* through the FileProvider (Open with, Share). A shared copy cannot be deleted the moment it is
|
||||
* handed over, nor when the screen that made it closes or the app starts again: the other app
|
||||
* may still be reading it (a mail being written). So it goes by its age alone, [SHARED_KEPT_MS]
|
||||
* after it was written -- looked at when the app starts, when a screen with transfers closes and
|
||||
* before a new copy is made -- and all of them go at sign-out and on a switch of instance. No
|
||||
* storage permission is involved: what the person keeps, they save through the system's own
|
||||
* "Save to" page.
|
||||
*/
|
||||
object FileCache {
|
||||
private const val VIEWING = "viewing"
|
||||
private const val SHARED = "shared"
|
||||
|
||||
/** How long a copy another app was handed is kept: an hour. */
|
||||
const val SHARED_KEPT_MS = 60 * 60 * 1000L
|
||||
|
||||
private fun dir(context: Context, name: String): File = File(context.cacheDir, name).apply { mkdirs() }
|
||||
|
||||
/** A new, empty place for one viewer's copy. */
|
||||
fun viewing(context: Context, name: String): File = File(dir(context, VIEWING), UUID.randomUUID().toString() + "-" + FileKinds.safeName(name, 80))
|
||||
|
||||
/** A new place for a copy another app will read, under its own name in a folder of its own. */
|
||||
fun shared(context: Context, name: String): File =
|
||||
File(File(dir(context, SHARED), UUID.randomUUID().toString()).apply { mkdirs() }, FileKinds.safeName(name))
|
||||
|
||||
/** Every copy, gone: at sign-out and on a switch of instance. */
|
||||
fun clear(context: Context) {
|
||||
for (name in listOf(VIEWING, SHARED)) runCatching { File(context.cacheDir, name).deleteRecursively() }
|
||||
}
|
||||
|
||||
/** When the process starts: no viewer is open, so their copies go; the shared ones by their age. */
|
||||
fun atStart(context: Context) {
|
||||
runCatching { File(context.cacheDir, VIEWING).deleteRecursively() }
|
||||
sweepShared(context)
|
||||
}
|
||||
|
||||
/** The shared copies older than [olderThanMs], and no other. */
|
||||
fun sweepShared(context: Context, olderThanMs: Long = SHARED_KEPT_MS) = sweep(File(context.cacheDir, SHARED), System.currentTimeMillis(), olderThanMs)
|
||||
|
||||
/**
|
||||
* Deletes what is directly in [dir] and was last written more than [olderThanMs] before
|
||||
* [now]. A copy's folder is as old as the newest thing in it: a long download's folder was
|
||||
* made when it began.
|
||||
*/
|
||||
fun sweep(dir: File, now: Long, olderThanMs: Long) {
|
||||
dir.listFiles()?.forEach { entry ->
|
||||
val written = maxOf(entry.lastModified(), entry.listFiles()?.maxOfOrNull { it.lastModified() } ?: 0L)
|
||||
if (now - written > olderThanMs) runCatching { entry.deleteRecursively() }
|
||||
}
|
||||
}
|
||||
|
||||
/** The address another app is given for a [shared] copy: the app's FileProvider, read-only, for that one grant. */
|
||||
fun uri(context: Context, file: File): Uri = FileProvider.getUriForFile(context, context.packageName + ".files", file)
|
||||
}
|
||||
|
||||
/** "Save to": the system's page for where a file goes (the Storage Access Framework), by a suggested name and type. */
|
||||
class CreateFile : ActivityResultContract<CreateFile.Ask, Uri?>() {
|
||||
data class Ask(val name: String, val mime: String)
|
||||
|
||||
override fun createIntent(context: Context, input: Ask): Intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
|
||||
.addCategory(Intent.CATEGORY_OPENABLE)
|
||||
.setType(input.mime.ifBlank { "application/octet-stream" })
|
||||
.putExtra(Intent.EXTRA_TITLE, input.name)
|
||||
|
||||
override fun parseResult(resultCode: Int, intent: Intent?): Uri? = intent?.data?.takeIf { resultCode == Activity.RESULT_OK }
|
||||
}
|
||||
|
||||
/** A file on the phone, as the picker or another app's share named it. */
|
||||
data class LocalFile(val uri: Uri, val name: String, val size: Long, val mime: String)
|
||||
|
||||
fun ContentResolver.describe(uri: Uri): LocalFile {
|
||||
var name: String? = null
|
||||
var size = -1L
|
||||
runCatching {
|
||||
query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
|
||||
if (c.moveToFirst()) {
|
||||
c.getColumnIndex(OpenableColumns.DISPLAY_NAME).takeIf { it >= 0 }?.let { name = c.getString(it) }
|
||||
c.getColumnIndex(OpenableColumns.SIZE).takeIf { it >= 0 && !c.isNull(it) }?.let { size = c.getLong(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
val said = name?.substringAfterLast('/')?.ifBlank { null } ?: uri.lastPathSegment?.substringAfterLast('/')?.ifBlank { null } ?: "upload"
|
||||
return LocalFile(uri, said, size, getType(uri) ?: "application/octet-stream")
|
||||
}
|
||||
|
||||
/**
|
||||
* A request body that reads [open]'s stream as it is sent: the file is never in memory whole.
|
||||
* [length] is its size when known (-1: sent chunked). [progress] hears how many bytes went.
|
||||
*/
|
||||
class StreamBody(
|
||||
private val type: MediaType?,
|
||||
private val length: Long,
|
||||
private val progress: (Long) -> Unit = {},
|
||||
private val open: () -> java.io.InputStream?,
|
||||
) : RequestBody() {
|
||||
override fun contentType(): MediaType? = type
|
||||
|
||||
override fun contentLength(): Long = length
|
||||
|
||||
/** The stream is read once: a failed upload is said, not silently sent again from a stream that may not open twice. */
|
||||
override fun isOneShot(): Boolean = true
|
||||
|
||||
override fun writeTo(sink: BufferedSink) {
|
||||
val stream = open() ?: throw IOException("The file could not be opened.")
|
||||
stream.source().use { source ->
|
||||
var sent = 0L
|
||||
while (true) {
|
||||
val n = source.read(sink.buffer, 64 * 1024L)
|
||||
if (n < 0) break
|
||||
sent += n
|
||||
sink.emitCompleteSegments()
|
||||
progress(sent)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload one file of the phone into [dir], streamed from its content address -- opened through
|
||||
* [SharedSource], so an address that leads to this app's own files is refused whoever named it.
|
||||
*/
|
||||
suspend fun ApiClient.uploadFrom(context: Context, file: LocalFile, dir: String, progress: (Long) -> Unit = {}): FileListing =
|
||||
uploadFile(dir, file.name, StreamBody(file.mime.toMediaTypeOrNull(), file.size, progress) { SharedSource.open(context, file.uri) })
|
||||
|
||||
/**
|
||||
* Download what [request] answers into the document [to] the person chose. A download that
|
||||
* fails or is given up leaves no half file behind where the provider lets it be removed.
|
||||
*/
|
||||
suspend fun ApiClient.downloadTo(context: Context, request: okhttp3.Request, to: Uri, progress: (Long, Long) -> Unit = { _, _ -> }) {
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
val out = context.contentResolver.openOutputStream(to, "w") ?: throw IOException("The file could not be written.")
|
||||
out.use { download(request, it, progress = progress) }
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
withContext(kotlinx.coroutines.NonCancellable + Dispatchers.IO) { runCatching { DocumentsContract.deleteDocument(context.contentResolver, to) } }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
/** A copy of what [request] answers in [file] (the private cache), at most [most] bytes. */
|
||||
suspend fun ApiClient.copyInto(request: okhttp3.Request, file: File, most: Long = Long.MAX_VALUE, progress: (Long, Long) -> Unit = { _, _ -> }): File {
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
file.parentFile?.mkdirs()
|
||||
file.outputStream().use { download(request, it, most, progress) }
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
withContext(kotlinx.coroutines.NonCancellable + Dispatchers.IO) { runCatching { file.delete() } }
|
||||
throw e
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
/** Hand [files] (cache copies) to another app: "Open with" for one, Share for one or several. Read-only, for this one grant. */
|
||||
object Handover {
|
||||
/**
|
||||
* "Open with" for the copy [file]. What it is offered as is read from the copy itself
|
||||
* ([openType]: its first bytes, else its name's extension) -- never the type the instance
|
||||
* said, which for a file an agent showed is one more thing a model had a hand in.
|
||||
*/
|
||||
fun view(context: Context, file: File): Intent {
|
||||
val uri = FileCache.uri(context, file)
|
||||
// A copy that cannot be read again is offered by its name alone.
|
||||
val head = try {
|
||||
file.inputStream().use { stream ->
|
||||
val bytes = ByteArray(SNIFF_BYTES)
|
||||
bytes.copyOf(stream.read(bytes).coerceAtLeast(0))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
ByteArray(0)
|
||||
}
|
||||
val named = MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.extension.lowercase())
|
||||
val intent = Intent(Intent.ACTION_VIEW).setDataAndType(uri, openType(head, named)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
return Intent.createChooser(intent, null)
|
||||
}
|
||||
|
||||
fun share(context: Context, files: List<File>, mime: String): Intent {
|
||||
val uris = files.map { FileCache.uri(context, it) }
|
||||
val intent = if (uris.size == 1) {
|
||||
Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uris[0])
|
||||
} else {
|
||||
Intent(Intent.ACTION_SEND_MULTIPLE).putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(uris))
|
||||
}
|
||||
intent.setType(mime.ifBlank { "*/*" }).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
// The chooser's own preview reads the address too: it is told through the clip.
|
||||
intent.clipData = ClipData.newRawUri(null, uris[0]).apply { uris.drop(1).forEach { addItem(ClipData.Item(it)) } }
|
||||
return Intent.createChooser(intent, null)
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a failure says the server has no such route at all (an older instance), rather than refusing. */
|
||||
fun noSuchRoute(e: Throwable): Boolean = e is ApiException && (e.status == 405 || (e.status == 404 && e.message == "Not Found"))
|
||||
|
||||
/** [report], heard only every quarter megabyte and at the end: a transfer does not redraw the screen for every packet. */
|
||||
fun stepped(report: (Long, Long) -> Unit): (Long, Long) -> Unit {
|
||||
var last = 0L
|
||||
return { done, total ->
|
||||
if (done - last >= 256 * 1024 || done == total) {
|
||||
last = done
|
||||
report(done, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ import androidx.compose.material.icons.filled.PushPin
|
||||
import androidx.compose.material.icons.filled.Schedule
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Summarize
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
@@ -72,25 +73,36 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ChatPage
|
||||
import eu.llembas.android.api.Doorstep
|
||||
import eu.llembas.android.api.Folder
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.ReplyFrame
|
||||
import eu.llembas.android.api.ReportsFrame
|
||||
import eu.llembas.android.api.SearchHit
|
||||
import eu.llembas.android.api.fit
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.signin.refusal
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
import java.time.Instant
|
||||
import java.time.LocalDate
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneId
|
||||
|
||||
data class ChatsState(
|
||||
@@ -103,8 +115,76 @@ data class ChatsState(
|
||||
/** Chats whose messages hold the search words (`GET /search?in=chats`), and the words asked. */
|
||||
val found: List<SearchHit> = emptyList(),
|
||||
val foundFor: String = "",
|
||||
/** How many reports are unread: the badge on Reports. */
|
||||
val unreadReports: Int = 0,
|
||||
/** Whether the instance has Reports at all: one before 2.0.0-beta.12 has no such page to open. */
|
||||
val reports: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* The events route's `reports` frame, as the drawer takes it: the badge is the server's count
|
||||
* of the unread, and an instance that sends the frame has Reports. Anything else it carries
|
||||
* (the newest report) is not the drawer's. A frame that cannot be read changes nothing.
|
||||
*/
|
||||
fun ChatsState.reported(data: String): ChatsState {
|
||||
val frame = runCatching { LembasJson.decodeFromString(ReportsFrame.serializer(), data) }.getOrNull() ?: return this
|
||||
return copy(unreadReports = frame.unread.coerceAtLeast(0), reports = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* The list's newest page read again ([page]), merged by id: the page's chats first, as the server
|
||||
* orders and marks them now (the one a reply just started in first, running or unread), then
|
||||
* every chat this list held that the page does not name, in the order it had. A chat that came
|
||||
* up from a later page a person had loaded is in the page, so it moves; the ones around its old
|
||||
* place stay. No chat is listed twice.
|
||||
*
|
||||
* The list is ordered by when a chat last changed, so the page holds every chat that changed
|
||||
* since its own last one did: a chat held here from after that moment which the page does not
|
||||
* name is no longer in the list (deleted, archived or filed away elsewhere), and goes. A page
|
||||
* with nothing after it is the whole list.
|
||||
*/
|
||||
fun ChatsState.withNewest(page: ChatPage): ChatsState {
|
||||
if (!page.more) return copy(chats = page.chats, more = false)
|
||||
val newest = page.chats.mapTo(HashSet()) { it.id }
|
||||
val floor = page.chats.lastOrNull()?.updatedAt?.let(::moment)
|
||||
val older = chats.filter { it.id !in newest && !gone(it, floor) }
|
||||
// Nothing below the page: whether there is more is the page's word.
|
||||
return copy(chats = page.chats + older, more = if (older.isEmpty()) page.more else more)
|
||||
}
|
||||
|
||||
/** Whether [chat], which the newest page does not name, changed after the page's last chat did ([floor]): it would be in the page were it still listed. */
|
||||
private fun gone(chat: Chat, floor: Instant?): Boolean {
|
||||
val changed = chat.updatedAt?.let(::moment) ?: return false
|
||||
return floor != null && changed.isAfter(floor)
|
||||
}
|
||||
|
||||
/** A time as the server writes it (ISO 8601 with an offset); null for anything else. */
|
||||
private fun moment(stamp: String): Instant? = runCatching { OffsetDateTime.parse(stamp).toInstant() }.getOrNull()
|
||||
|
||||
/**
|
||||
* Whether the events route's `reply` frame [said] asks for the list to be read again. Only
|
||||
* while something shows the list ([shown]; the drawer reads it whenever it opens), and only for
|
||||
* what the list does not show already: a reply that started in a chat whose row says it is
|
||||
* running is no news (every reconnection of the route says all of those again), and the end
|
||||
* of a reply in a chat that is listed is marked on its row without a read ([ended]). A list
|
||||
* not read yet is left to its first read.
|
||||
*/
|
||||
fun ChatsState.readsFor(said: ReplyFrame, shown: Boolean): Boolean {
|
||||
if (!shown || chats.isEmpty() || said.chatId.isBlank()) return false
|
||||
val row = chats.firstOrNull { it.id == said.chatId }
|
||||
return if (said.live) row?.running != true else row == null
|
||||
}
|
||||
|
||||
/**
|
||||
* A reply ended in the chat [said] names (`live` false): its row is no longer running, and shows
|
||||
* that it has something new -- unless it is the chat [open] on screen, where the person watched
|
||||
* it end. Nothing is read for it.
|
||||
*/
|
||||
fun ChatsState.ended(said: ReplyFrame, open: String?): ChatsState {
|
||||
if (said.live || chats.none { it.id == said.chatId }) return this
|
||||
return copy(chats = chats.map { if (it.id == said.chatId) it.copy(running = false, unread = it.unread || it.id != open) else it })
|
||||
}
|
||||
|
||||
/** The drawer's list: every chat of the instance in use, both kinds, newest first. */
|
||||
class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ChatsState())
|
||||
@@ -132,16 +212,154 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
_state.value = ChatsState(error = getApplication<Application>().getString(said))
|
||||
return@launch
|
||||
}
|
||||
val told = reportsTold
|
||||
val page = api.chats()
|
||||
// Folders are a side dish: the chats show without them if they cannot be read.
|
||||
val folders = runCatching { api.folders() }.getOrDefault(_state.value.folders)
|
||||
_state.value = ChatsState(chats = page.chats, more = page.more, folders = folders)
|
||||
// So is the count of unread reports: an instance before Reports simply has none.
|
||||
val unread = runCatching { api.unreadReports() }
|
||||
// No such route (404, 405): no Reports. Any other trouble leaves what was known.
|
||||
val refused = (unread.exceptionOrNull() as? ApiException)?.status
|
||||
val has = if (unread.isSuccess) {
|
||||
true
|
||||
} else if (refused == 404 || refused == 405) {
|
||||
false
|
||||
} else {
|
||||
_state.value.reports
|
||||
}
|
||||
// The events route may have said the count while this was being read: its
|
||||
// word is the newer one, and a slow read does not write over it.
|
||||
val newer = reportsTold != told
|
||||
_state.value = ChatsState(
|
||||
chats = page.chats,
|
||||
more = page.more,
|
||||
folders = folders,
|
||||
unreadReports = if (newer) _state.value.unreadReports else unread.getOrDefault(_state.value.unreadReports),
|
||||
reports = has || (newer && _state.value.reports),
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow the person's events route while the app is in front, for its `reports` frame: the
|
||||
* badge on Reports moves when a report arrives or is read anywhere, not only when the drawer
|
||||
* opens. Runs until cancelled. An older server has no such route, or no such frame: the
|
||||
* badge is then what the drawer's own read said.
|
||||
*/
|
||||
suspend fun watchReports() {
|
||||
val app = getApplication<Application>().lembas
|
||||
// What one instance proved about its frames says nothing of another.
|
||||
val instance = app.instances.current()?.id
|
||||
if (instance != endsOf) {
|
||||
ends = ReplyEnds()
|
||||
endsOf = instance
|
||||
}
|
||||
val frames = runCatching { app.eventFrames() }.getOrNull() ?: return
|
||||
try {
|
||||
frames.collect { frame ->
|
||||
// An instance this app refuses shows its refusal and nothing else.
|
||||
if (frame.event == "reports" && refused == null) {
|
||||
reportsTold++
|
||||
_state.update { it.reported(frame.data) }
|
||||
}
|
||||
if (frame.event == "reply" && refused == null) replySaid(frame.data)
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// Nothing to say: the count is read when the drawer opens, as before.
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the list is on screen (the drawer is open): only then is it read again by itself. */
|
||||
private var shown = false
|
||||
|
||||
/** The chat open on screen, by its id: the end of its reply is not something new. */
|
||||
var open: String? = null
|
||||
|
||||
/** Whether this instance says when replies end; until it has, a running row is read again now and then. */
|
||||
private var ends = ReplyEnds()
|
||||
|
||||
/** The instance [ends] is about, by its id. */
|
||||
private var endsOf: String? = null
|
||||
|
||||
fun shown(now: Boolean) {
|
||||
shown = now
|
||||
// What was asked for while it was open is the next opening's read.
|
||||
if (!now) soon.forget()
|
||||
}
|
||||
|
||||
/**
|
||||
* The events route said a reply started or ended in one of the person's chats. An end is
|
||||
* marked on the chat's row at once, with no read; a start in a chat the list does not show
|
||||
* as running moves that chat up and gives it its dot at the list's next read, shortly --
|
||||
* while the drawer is open. Closed, nothing is read: it reads the list when it opens.
|
||||
*/
|
||||
private fun replySaid(data: String) {
|
||||
val said = runCatching { LembasJson.decodeFromString(ReplyFrame.serializer(), data) }.getOrNull() ?: return
|
||||
ends.hear(said)
|
||||
val reads = _state.value.readsFor(said, shown)
|
||||
if (!said.live) _state.update { it.ended(said, open) }
|
||||
if (reads) soon.ask()
|
||||
}
|
||||
|
||||
/**
|
||||
* The newest page of the list, read once things have been quiet for a moment: several
|
||||
* replies starting together (a queue, a team) are one read, and a run of them that never
|
||||
* falls quiet still gets one every few seconds. It waits at the gate, so a frame heard just
|
||||
* before the phone locked or the app left the front is one read on the return, not a
|
||||
* request behind the lock. A read under way is never cut short by the next frame.
|
||||
*/
|
||||
private val soon by lazy {
|
||||
Soon(viewModelScope, LIST_PAUSE_MS, LIST_MOST_MS, before = { getApplication<Application>().lembas.gate.pass() }) { readNewest() }
|
||||
}
|
||||
|
||||
private val reading = Mutex()
|
||||
|
||||
/** The list's newest page, merged into what is shown. A list not read yet is left to its first read. */
|
||||
private suspend fun readNewest() = reading.withLock {
|
||||
if (refused != null || _state.value.chats.isEmpty()) return@withLock
|
||||
val page = try {
|
||||
getApplication<Application>().lembas.instances.client()?.chats()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
} ?: return@withLock
|
||||
_state.update { it.withNewest(page) }
|
||||
}
|
||||
|
||||
/**
|
||||
* While the list is on screen and the app in front: an instance that does not say when a
|
||||
* reply ends leaves a row's running mark as old as the list's last read, so while any row
|
||||
* shows one the list is read again at a bounded rate ([runningPause]), at the gate, and no
|
||||
* more once none does. An instance that says the ends ([ReplyEnds]) is never asked: its
|
||||
* frames clear the marks. Runs until cancelled (the drawer closed, the app left the front).
|
||||
*/
|
||||
suspend fun watchRunning() {
|
||||
val gate = getApplication<Application>().lembas.gate
|
||||
var round = 0
|
||||
while (true) {
|
||||
_state.first { state -> state.chats.any { it.running } }
|
||||
if (ends.said) return
|
||||
delay(runningPause(round))
|
||||
gate.pass()
|
||||
if (ends.said) return
|
||||
if (_state.value.chats.none { it.running }) {
|
||||
round = 0
|
||||
continue
|
||||
}
|
||||
round++
|
||||
readNewest()
|
||||
}
|
||||
}
|
||||
|
||||
/** How many `reports` frames have come: a list read that began before the last one is older than it. */
|
||||
private var reportsTold = 0
|
||||
|
||||
fun more() {
|
||||
val last = _state.value.chats.lastOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
@@ -248,6 +466,12 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
private const val SEARCH_PAUSE_MS = 400L
|
||||
|
||||
/** Between a `reply` frame and the list's read: a reply is said about a quarter of a second after it starts. */
|
||||
private const val LIST_PAUSE_MS = 1500L
|
||||
|
||||
/** The longest a read of the list waits for the replies' frames to fall quiet. */
|
||||
private const val LIST_MOST_MS = 6000L
|
||||
|
||||
/** Where the drawer can go, besides a chat. */
|
||||
interface DrawerActions {
|
||||
fun newChat() {}
|
||||
@@ -262,6 +486,7 @@ interface DrawerActions {
|
||||
fun deleteFolder(folder: Folder) {}
|
||||
fun files() {}
|
||||
fun scheduled() {}
|
||||
fun reports() {}
|
||||
fun archived() {}
|
||||
fun memory() {}
|
||||
fun settings() {}
|
||||
@@ -331,6 +556,9 @@ fun DrawerContent(
|
||||
item { DrawerItem(Icons.Filled.EditNote, stringResource(R.string.new_chat), onClick = actions::newChat) }
|
||||
item { DrawerItem(Icons.Filled.Terminal, stringResource(R.string.new_agent_chat), onClick = actions::newAgentChat) }
|
||||
item { DrawerItem(Icons.Filled.Folder, stringResource(R.string.files), onClick = actions::files) }
|
||||
if (state.reports) {
|
||||
item { DrawerItem(Icons.Filled.Summarize, stringResource(R.string.reports), badge = state.unreadReports, onClick = actions::reports) }
|
||||
}
|
||||
item { DrawerItem(Icons.Filled.Schedule, stringResource(R.string.scheduled), onClick = actions::scheduled) }
|
||||
item { DrawerItem(Icons.Filled.Inventory2, stringResource(R.string.archived), onClick = actions::archived) }
|
||||
item { DrawerItem(Icons.Filled.Psychology, stringResource(R.string.memory), onClick = actions::memory) }
|
||||
@@ -613,7 +841,7 @@ private fun FolderNameDialog(initial: String, title: Int, onSave: (String) -> Un
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DrawerItem(icon: ImageVector, label: String, subtitle: String? = null, onClick: () -> Unit) {
|
||||
private fun DrawerItem(icon: ImageVector, label: String, subtitle: String? = null, badge: Int = 0, onClick: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
@@ -628,6 +856,13 @@ private fun DrawerItem(icon: ImageVector, label: String, subtitle: String? = nul
|
||||
Text(label, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
subtitle?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) }
|
||||
}
|
||||
// A count of what is new: the words give, the badge keeps its size.
|
||||
if (badge > 0) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Box(Modifier.background(palette.accent, RoundedCornerShape(50)).padding(horizontal = 8.dp, vertical = 2.dp)) {
|
||||
Text(if (badge > 99) "99+" else badge.toString(), style = MaterialTheme.typography.labelMedium, color = palette.bg, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package eu.llembas.android.ui.home
|
||||
|
||||
import eu.llembas.android.api.ReplyFrame
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Something done shortly after it was asked for, once for many askings: [work] runs when nobody
|
||||
* has asked for [pause] milliseconds, and at the latest [most] milliseconds after the first
|
||||
* asking -- so a stream of askings closer together than the pause (a team's replies starting
|
||||
* one after another) still gets its work, every [most], instead of none until it falls quiet.
|
||||
*
|
||||
* Work under way is never cancelled by a new asking; an asking that comes while it runs is
|
||||
* answered by one more run after it. [before] is what the work waits for before it starts (its
|
||||
* turn at the gate): an asking during that wait is still answered by the run it waits for.
|
||||
*
|
||||
* Everything here runs on [scope]'s one thread.
|
||||
*/
|
||||
class Soon(
|
||||
private val scope: CoroutineScope,
|
||||
private val pause: Long,
|
||||
private val most: Long,
|
||||
private val before: suspend () -> Unit = {},
|
||||
private val work: suspend () -> Unit,
|
||||
) {
|
||||
private var quiet: Job? = null
|
||||
private var latest: Job? = null
|
||||
|
||||
/** Whether a run is under way, from before its turn to its end. */
|
||||
private var running = false
|
||||
|
||||
/** Whether the run under way has started its work: an asking from then on is newer than it. */
|
||||
private var started = false
|
||||
private var again = false
|
||||
|
||||
fun ask() {
|
||||
if (running) {
|
||||
if (started) again = true
|
||||
return
|
||||
}
|
||||
quiet?.cancel()
|
||||
quiet = scope.launch {
|
||||
delay(pause)
|
||||
run()
|
||||
}
|
||||
if (latest?.isActive != true) {
|
||||
latest = scope.launch {
|
||||
delay(most)
|
||||
run()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What was asked for and has not started is dropped (nobody is looking any more); work under way finishes. */
|
||||
fun forget() {
|
||||
quiet?.cancel()
|
||||
latest?.cancel()
|
||||
quiet = null
|
||||
latest = null
|
||||
again = false
|
||||
}
|
||||
|
||||
private fun run() {
|
||||
if (running) return
|
||||
val timers = listOf(quiet, latest)
|
||||
quiet = null
|
||||
latest = null
|
||||
started = false
|
||||
running = true
|
||||
// Not a child of either timer: cancelling them below must not reach the work.
|
||||
scope.launch {
|
||||
try {
|
||||
before()
|
||||
started = true
|
||||
work()
|
||||
} finally {
|
||||
running = false
|
||||
if (again) {
|
||||
again = false
|
||||
ask()
|
||||
}
|
||||
}
|
||||
}
|
||||
// One of the two is the caller; it has nothing left to do.
|
||||
timers.forEach { it?.cancel() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the instance says when a reply ends: the events route's `reply` frame with `live`
|
||||
* false, for a reply it had said was being written. One such frame is the proof, and from then
|
||||
* on the list's running marks are cleared by the frames alone. An instance from before that
|
||||
* never proves it, and the list is read again now and then instead ([runningPause]).
|
||||
*/
|
||||
class ReplyEnds {
|
||||
private val started = LinkedHashSet<String>()
|
||||
|
||||
var said = false
|
||||
private set
|
||||
|
||||
fun hear(frame: ReplyFrame) {
|
||||
if (frame.messageId.isBlank()) return
|
||||
if (frame.live) {
|
||||
started += frame.messageId
|
||||
if (started.size > REMEMBERED) started.remove(started.first())
|
||||
} else if (started.remove(frame.messageId)) {
|
||||
said = true
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val REMEMBERED = 64
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How long to wait before the list is read again because a row shows a reply being written and
|
||||
* nothing has said it ended: 5, 10, 20, 40 seconds, then every minute ([round] counts the
|
||||
* reads since a row last showed one). A bounded rate, and only while such a row is on screen.
|
||||
*/
|
||||
fun runningPause(round: Int): Long = (5_000L shl round.coerceIn(0, 4)).coerceAtMost(60_000L)
|
||||
@@ -0,0 +1,437 @@
|
||||
@file:OptIn(ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.reports
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Intent
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Reply
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.DoneAll
|
||||
import androidx.compose.material.icons.filled.PriorityHigh
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SwipeToDismissBox
|
||||
import androidx.compose.material3.SwipeToDismissBoxValue
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
|
||||
import androidx.compose.material3.rememberSwipeToDismissBoxState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Report
|
||||
import eu.llembas.android.api.sortedReports
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.ui.chat.RichMarkdown
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.pageProjection
|
||||
import eu.llembas.android.ui.scheduled.BackBar
|
||||
import eu.llembas.android.ui.scheduled.ScheduleLogic
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private suspend fun Application.api(): ApiClient = lembas.instances.client() ?: throw ApiException(401, "Not signed in.")
|
||||
|
||||
/** A server without the reports routes answers 404 (or 405): it is older, not broken. */
|
||||
private fun Throwable.unsupported(): Boolean = this is ApiException && (status == 404 || status == 405)
|
||||
|
||||
// --- The list --------------------------------------------------------------------------------
|
||||
|
||||
data class ReportsState(
|
||||
val reports: List<Report> = emptyList(),
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** The instance is older than Reports: said plainly, instead of an error. */
|
||||
val unsupported: Boolean = false,
|
||||
)
|
||||
|
||||
class ReportsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ReportsState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
fun load() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val reports = getApplication<Application>().api().reports()
|
||||
_state.value = ReportsState(reports = sortedReports(reports))
|
||||
} catch (e: Exception) {
|
||||
_state.update {
|
||||
it.copy(loading = false, unsupported = e.unsupported(), error = if (e.unsupported()) null else getApplication<Application>().explain(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Read: it stays in the list, among those read. A failure is put right by reading the list again. */
|
||||
fun markRead(report: Report) {
|
||||
_state.update { s -> s.copy(reports = sortedReports(s.reports.map { if (it.id == report.id) it.copy(unread = false) else it })) }
|
||||
Notifications.reportSeen(getApplication(), report.id)
|
||||
viewModelScope.launch { runCatching { getApplication<Application>().api().readReport(report.id) }.onFailure { fail(it) } }
|
||||
}
|
||||
|
||||
fun delete(report: Report) {
|
||||
_state.update { s -> s.copy(reports = s.reports.filterNot { it.id == report.id }) }
|
||||
Notifications.reportSeen(getApplication(), report.id)
|
||||
viewModelScope.launch { runCatching { getApplication<Application>().api().deleteReport(report.id) }.onFailure { fail(it) } }
|
||||
}
|
||||
|
||||
private fun fail(e: Throwable) {
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
|
||||
load()
|
||||
}
|
||||
}
|
||||
|
||||
interface ReportsActions {
|
||||
fun open(report: Report) {}
|
||||
fun markRead(report: Report) {}
|
||||
fun delete(report: Report) {}
|
||||
fun reload() {}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ReportsScreen(onBack: () -> Unit, onOpen: (String) -> Unit, model: ReportsViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
// Read again each time the page comes up: a report opened and read is no longer bold on the way back.
|
||||
LaunchedEffect(Unit) { model.load() }
|
||||
ReportsContent(
|
||||
state,
|
||||
object : ReportsActions {
|
||||
override fun open(report: Report) = onOpen(report.id)
|
||||
|
||||
override fun markRead(report: Report) = model.markRead(report)
|
||||
|
||||
override fun delete(report: Report) = model.delete(report)
|
||||
|
||||
override fun reload() = model.load()
|
||||
},
|
||||
onBack,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports: what scheduled tasks had to tell. The unread first; each row its title, the task it
|
||||
* came from and when, with a mark where the model called it important. Pull to read the list
|
||||
* again; swipe a row one way to mark it read, the other to delete it (which asks once).
|
||||
*/
|
||||
@Composable
|
||||
fun ReportsContent(state: ReportsState, actions: ReportsActions, onBack: () -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
var deleting by remember { mutableStateOf<Report?>(null) }
|
||||
deleting?.let { report ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { deleting = null },
|
||||
title = { Text(stringResource(R.string.report_delete_title)) },
|
||||
text = { Text(stringResource(R.string.report_delete_line, report.title.ifBlank { stringResource(R.string.report_untitled) })) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
deleting = null
|
||||
actions.delete(report)
|
||||
}) { Text(stringResource(R.string.delete), color = palette.danger) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { deleting = null }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
Scaffold(containerColor = palette.bg, topBar = { BackBar(stringResource(R.string.reports), onBack) }) { padding ->
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = actions::reload, modifier = Modifier.fillMaxSize().padding(padding)) {
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
state.error?.let { error ->
|
||||
item {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(error, color = palette.danger, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
TextButton(onClick = actions::reload) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.reports.isEmpty() && !state.loading && state.error == null) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(if (state.unsupported) R.string.reports_unsupported else R.string.reports_none),
|
||||
color = palette.inkMuted,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.padding(vertical = 16.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
items(state.reports, key = { it.id }) { report ->
|
||||
ReportRow(report, onOpen = { actions.open(report) }, onRead = { actions.markRead(report) }, onDelete = { deleting = report })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One report in the list. Swiping never removes the row by itself: towards the end marks it read,
|
||||
* towards the start asks whether to delete it, and either way the row comes back to rest.
|
||||
*/
|
||||
@Composable
|
||||
private fun ReportRow(report: Report, onOpen: () -> Unit, onRead: () -> Unit, onDelete: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val swipe = rememberSwipeToDismissBoxState(
|
||||
confirmValueChange = { to ->
|
||||
when (to) {
|
||||
SwipeToDismissBoxValue.StartToEnd -> if (report.unread) onRead()
|
||||
SwipeToDismissBoxValue.EndToStart -> onDelete()
|
||||
SwipeToDismissBoxValue.Settled -> Unit
|
||||
}
|
||||
false
|
||||
},
|
||||
)
|
||||
SwipeToDismissBox(
|
||||
state = swipe,
|
||||
enableDismissFromStartToEnd = report.unread,
|
||||
backgroundContent = {
|
||||
val deletes = swipe.dismissDirection == SwipeToDismissBoxValue.EndToStart
|
||||
Row(
|
||||
Modifier.fillMaxSize().background(
|
||||
if (deletes) palette.dangerSoft else palette.surfaceActive,
|
||||
RoundedCornerShape(16.dp),
|
||||
).padding(horizontal = 20.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = if (deletes) Arrangement.End else Arrangement.Start,
|
||||
) {
|
||||
Icon(
|
||||
if (deletes) Icons.Filled.Delete else Icons.Filled.DoneAll,
|
||||
contentDescription = stringResource(if (deletes) R.string.delete else R.string.report_mark_read),
|
||||
tint = if (deletes) palette.danger else palette.inkMuted,
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(palette.surfaceRaised, RoundedCornerShape(16.dp))
|
||||
.clickable(onClick = onOpen)
|
||||
.heightIn(min = 72.dp)
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.Top,
|
||||
) {
|
||||
// The unread dot's place is kept for a read row too, so the titles start on one line.
|
||||
Box(Modifier.padding(top = 6.dp).size(10.dp).background(if (report.unread) palette.accent else palette.surfaceRaised, CircleShape))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
report.title.ifBlank { stringResource(R.string.report_untitled) },
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = if (report.unread) FontWeight.SemiBold else FontWeight.Normal,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
ReportFacts(report)
|
||||
if (report.summary.isNotBlank()) {
|
||||
Text(report.summary, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
if (report.high) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(
|
||||
Icons.Filled.PriorityHigh,
|
||||
contentDescription = stringResource(R.string.report_important),
|
||||
tint = palette.warning,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Under a report's title: the task it came from, and when. */
|
||||
@Composable
|
||||
private fun ReportFacts(report: Report) {
|
||||
val palette = LocalPalette.current
|
||||
val facts = listOfNotNull(report.from.ifBlank { null }, ScheduleLogic.moment(report.created)).joinToString(" · ")
|
||||
if (facts.isNotBlank()) Text(facts, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
|
||||
// --- One report ------------------------------------------------------------------------------
|
||||
|
||||
data class ReportState(val report: Report? = null, val loading: Boolean = true, val error: String? = null, val replying: Boolean = false)
|
||||
|
||||
class ReportViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ReportState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
/** Read the report, and mark it read: opening it is reading it. */
|
||||
fun load(id: String) {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().api()
|
||||
val report = api.report(id)
|
||||
_state.value = ReportState(report = report.copy(unread = false), loading = false)
|
||||
// Read here: its notification, if one is still up, goes.
|
||||
Notifications.reportSeen(getApplication(), id)
|
||||
if (report.unread) runCatching { api.readReport(id) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Reply: the server continues the report as a conversation and says which chat it is. */
|
||||
fun reply(then: (chat: String, title: String) -> Unit) {
|
||||
val report = _state.value.report ?: return
|
||||
// A reply that was begun before goes on in its chat: nothing is asked of the server.
|
||||
report.chatId?.let { return then(it, report.title) }
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(replying = true, error = null) }
|
||||
try {
|
||||
val chat = getApplication<Application>().api().replyToReport(report.id) ?: throw ApiException(502, "")
|
||||
_state.update { it.copy(replying = false) }
|
||||
then(chat, report.title)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(replying = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ReportScreen(id: String, onBack: () -> Unit, onReply: (chat: String, title: String) -> Unit, model: ReportViewModel = viewModel(key = "report-$id")) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val context = LocalContext.current
|
||||
LaunchedEffect(id) { model.load(id) }
|
||||
ReportContent(
|
||||
state,
|
||||
onBack = onBack,
|
||||
onRetry = { model.load(id) },
|
||||
onReply = { model.reply(onReply) },
|
||||
onShare = { report ->
|
||||
val send = Intent(
|
||||
Intent.ACTION_SEND,
|
||||
).setType("text/plain").putExtra(Intent.EXTRA_SUBJECT, report.title).putExtra(Intent.EXTRA_TEXT, shareText(report))
|
||||
runCatching { context.startActivity(Intent.createChooser(send, null)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** What Share hands over: the title, then the report as text -- a page in it as its one line, never its source. */
|
||||
fun shareText(report: Report): String {
|
||||
// The server's own text of the body where it sends one; else the same made here.
|
||||
val text = report.text?.trim()?.ifBlank { null } ?: pageProjection(report.body.orEmpty(), untitled = "Page")
|
||||
return listOf(report.title, text).filter { it.isNotBlank() }.joinToString("\n\n")
|
||||
}
|
||||
|
||||
/**
|
||||
* A report, read as a page: its title, where it came from and when, then the body -- Markdown a
|
||||
* model wrote, drawn as the chat draws a reply (untrusted: no images, no HTML; a page in it is a
|
||||
* card, not a page). Reply stays at the foot; Share is in the bar.
|
||||
*/
|
||||
@Composable
|
||||
fun ReportContent(state: ReportState, onBack: () -> Unit = {}, onRetry: () -> Unit = {}, onReply: () -> Unit = {}, onShare: (Report) -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
val report = state.report
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
topBar = {
|
||||
BackBar(stringResource(R.string.report), onBack) {
|
||||
if (report !=
|
||||
null
|
||||
) {
|
||||
IconButton(onClick = { onShare(report) }) { Icon(Icons.Filled.Share, contentDescription = stringResource(R.string.report_share)) }
|
||||
}
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
if (report != null) {
|
||||
Box(Modifier.background(palette.bg).navigationBarsPadding().padding(16.dp)) {
|
||||
Button(onClick = onReply, enabled = !state.replying, modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp)) {
|
||||
if (state.replying) {
|
||||
CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
|
||||
} else {
|
||||
Icon(Icons.AutoMirrored.Filled.Reply, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.report_reply))
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
state.error?.let { error ->
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(error, color = palette.danger, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
if (report == null) TextButton(onClick = onRetry) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
}
|
||||
if (report == null) {
|
||||
if (state.loading) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(24.dp))
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.Top) {
|
||||
Text(
|
||||
report.title.ifBlank { stringResource(R.string.report_untitled) },
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (report.high) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(Icons.Filled.PriorityHigh, contentDescription = stringResource(R.string.report_important), tint = palette.warning)
|
||||
}
|
||||
}
|
||||
ReportFacts(report)
|
||||
// The server's own text of the body, where each page is its one line; else the body.
|
||||
RichMarkdown((report.text?.ifBlank { null } ?: report.body.orEmpty()).ifBlank { report.summary })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.RunResult
|
||||
import eu.llembas.android.api.SchedulingModel
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.chat.LocalCopy
|
||||
import eu.llembas.android.ui.chat.RichMarkdown
|
||||
@@ -49,7 +50,14 @@ import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class RunState(val title: String = "", val result: RunResult? = null, val loading: Boolean = false, val error: String? = null)
|
||||
data class RunState(
|
||||
val title: String = "",
|
||||
val result: RunResult? = null,
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** The models scheduled work may run on, for naming the run's by its connection. */
|
||||
val models: List<SchedulingModel> = emptyList(),
|
||||
)
|
||||
|
||||
class RunViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(RunState())
|
||||
@@ -64,6 +72,7 @@ class RunViewModel(app: Application) : AndroidViewModel(app) {
|
||||
val result = api.scheduleRun(schedule, run)
|
||||
val title = runCatching { api.schedule(schedule).title }.getOrDefault("")
|
||||
_state.update { it.copy(result = result, title = title, loading = false) }
|
||||
runCatching { api.schedulingModels() }.onSuccess { m -> _state.update { it.copy(models = m.models) } }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
@@ -77,6 +86,7 @@ fun RunScreen(
|
||||
runId: String,
|
||||
onBack: () -> Unit,
|
||||
onOpenChat: (String) -> Unit,
|
||||
onOpenReport: (String) -> Unit = {},
|
||||
model: RunViewModel = viewModel(key = "run-$scheduleId-$runId"),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
@@ -84,7 +94,7 @@ fun RunScreen(
|
||||
model.open(scheduleId, runId)
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
RunContent(state, onBack = onBack, onOpenChat = onOpenChat)
|
||||
RunContent(state, onBack = onBack, onOpenChat = onOpenChat, onOpenReport = onOpenReport)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,7 +103,7 @@ fun RunScreen(
|
||||
* links only outside) -- or why there is none. Open its chat goes on from there.
|
||||
*/
|
||||
@Composable
|
||||
fun RunContent(state: RunState, onBack: () -> Unit = {}, onOpenChat: (String) -> Unit = {}) {
|
||||
fun RunContent(state: RunState, onBack: () -> Unit = {}, onOpenChat: (String) -> Unit = {}, onOpenReport: (String) -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val copy: (String) -> Unit = remember(context) {
|
||||
@@ -127,7 +137,9 @@ fun RunContent(state: RunState, onBack: () -> Unit = {}, onOpenChat: (String) ->
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
RunFacts(run, withPreview = false)
|
||||
RunFacts(run, withPreview = false, models = state.models)
|
||||
// What the run filed for the person, when it filed anything.
|
||||
run.reportId?.let { report -> ReportLink(onClick = { onOpenReport(report) }) }
|
||||
}
|
||||
}
|
||||
Header(stringResource(R.string.run_result))
|
||||
|
||||
@@ -4,9 +4,12 @@ package eu.llembas.android.ui.scheduled
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
@@ -23,6 +26,7 @@ import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
@@ -30,20 +34,24 @@ import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Computer
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.Pause
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Schedule
|
||||
import androidx.compose.material.icons.filled.Summarize
|
||||
import androidx.compose.material.icons.filled.Tune
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
@@ -62,8 +70,11 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -75,15 +86,26 @@ import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.DeviceDirectory
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.RanOn
|
||||
import eu.llembas.android.api.RunsOn
|
||||
import eu.llembas.android.api.Schedule
|
||||
import eu.llembas.android.api.ScheduleCompiled
|
||||
import eu.llembas.android.api.ScheduleRun
|
||||
import eu.llembas.android.api.SchedulesFrame
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.SchedulingModel
|
||||
import eu.llembas.android.api.WatchCommand
|
||||
import eu.llembas.android.api.WhereToRun
|
||||
import eu.llembas.android.api.agentic
|
||||
import eu.llembas.android.api.computerAway
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.api.notifyChoice
|
||||
import eu.llembas.android.api.saidWithConnection
|
||||
import eu.llembas.android.api.titleAmong
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.DirectoryPicker
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.progressLineOf
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
@@ -95,6 +117,9 @@ import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Whether the Scheduled list starts listening to the events route now: only [inFront], and only once ([listening]). */
|
||||
fun listens(inFront: Boolean, listening: Boolean): Boolean = inFront && !listening
|
||||
|
||||
/** A server without the scheduling routes answers 404 (or 405): it is older, not broken. */
|
||||
private fun Throwable.unsupported(): Boolean = this is ApiException && (status == 404 || status == 405)
|
||||
|
||||
@@ -115,6 +140,19 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
private var live: Job? = null
|
||||
|
||||
/**
|
||||
* Whether the list is on screen, in front. The events route is listened to only then: a read
|
||||
* that comes back after the screen was left (or the phone locked) must not open it, for
|
||||
* nothing would close it again while this model lives.
|
||||
*/
|
||||
private var front = false
|
||||
|
||||
/** The screen came to the front: the list is read, and followed until [stop]. */
|
||||
fun shown() {
|
||||
front = true
|
||||
load()
|
||||
}
|
||||
|
||||
fun load() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
@@ -142,11 +180,12 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
* Without it the list is what the last read said, and a pull reads it again.
|
||||
*/
|
||||
private fun watch() {
|
||||
if (live?.isActive == true) return
|
||||
if (!listens(front, live?.isActive == true)) return
|
||||
live = viewModelScope.launch {
|
||||
val client = runCatching { getApplication<Application>().api() }.getOrNull() ?: return@launch
|
||||
// The one connection the drawer's badge listens on too (`EventsHub`).
|
||||
val frames = runCatching { getApplication<Application>().lembas.eventFrames() }.getOrNull() ?: return@launch
|
||||
try {
|
||||
StreamClient(client).watch { client.events() }.collect { frame ->
|
||||
frames.collect { frame ->
|
||||
if (frame.event != "schedules") return@collect
|
||||
val read = runCatching { LembasJson.decodeFromString(SchedulesFrame.serializer(), frame.data) }.getOrNull() ?: return@collect
|
||||
_state.update { it.copy(schedules = read.schedules) }
|
||||
@@ -160,6 +199,7 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
front = false
|
||||
live?.cancel()
|
||||
live = null
|
||||
}
|
||||
@@ -187,7 +227,7 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
fun ScheduledScreen(onBack: () -> Unit, onOpen: (String) -> Unit, onNew: () -> Unit, onModels: () -> Unit, model: ScheduledViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LifecycleResumeEffect(Unit) {
|
||||
model.load()
|
||||
model.shown()
|
||||
onPauseOrDispose { model.stop() }
|
||||
}
|
||||
ScheduledContent(state, onBack = onBack, onOpen = onOpen, onNew = onNew, onModels = onModels, onPause = model::pause, onRetry = model::load)
|
||||
@@ -359,6 +399,8 @@ data class ScheduleState(
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
val notice: String? = null,
|
||||
/** The models scheduled work may run on: what tells two with one id apart by their connection. */
|
||||
val models: List<SchedulingModel> = emptyList(),
|
||||
)
|
||||
|
||||
class ScheduleViewModel(app: Application) : AndroidViewModel(app) {
|
||||
@@ -375,6 +417,7 @@ class ScheduleViewModel(app: Application) : AndroidViewModel(app) {
|
||||
val schedule = api.schedule(id)
|
||||
val runs = runCatching { api.scheduleRuns(id) }.getOrNull()
|
||||
_state.update { it.copy(schedule = schedule, runs = runs?.runs.orEmpty(), more = runs?.more == true, loading = false) }
|
||||
runCatching { api.schedulingModels() }.onSuccess { m -> _state.update { it.copy(models = m.models) } }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
@@ -424,6 +467,7 @@ fun ScheduleScreen(
|
||||
onBack: () -> Unit,
|
||||
onEdit: (String) -> Unit,
|
||||
onOpenRun: (String) -> Unit,
|
||||
onOpenReport: (String) -> Unit = {},
|
||||
model: ScheduleViewModel = viewModel(key = "schedule-$id"),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
@@ -447,6 +491,7 @@ fun ScheduleScreen(
|
||||
onRunNow = model::runNow,
|
||||
onPause = model::pause,
|
||||
onOpenRun = { run -> onOpenRun(run.id) },
|
||||
onOpenReport = onOpenReport,
|
||||
onMore = model::more,
|
||||
)
|
||||
}
|
||||
@@ -466,6 +511,7 @@ fun ScheduleContent(
|
||||
onRunNow: () -> Unit = {},
|
||||
onPause: (Boolean) -> Unit = {},
|
||||
onOpenRun: (ScheduleRun) -> Unit = {},
|
||||
onOpenReport: (String) -> Unit = {},
|
||||
onMore: () -> Unit = {},
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
@@ -488,7 +534,7 @@ fun ScheduleContent(
|
||||
if (state.loading) CircularProgressIndicator() else state.error?.let { Message(it) }
|
||||
}
|
||||
} else {
|
||||
ScheduleBody(state, schedule, padding, onRunNow, onPause, onOpenRun, onMore)
|
||||
ScheduleBody(state, schedule, padding, onRunNow, onPause, onOpenRun, onOpenReport, onMore)
|
||||
}
|
||||
}
|
||||
if (deleting) {
|
||||
@@ -514,6 +560,7 @@ private fun ScheduleBody(
|
||||
onRunNow: () -> Unit,
|
||||
onPause: (Boolean) -> Unit,
|
||||
onOpenRun: (ScheduleRun) -> Unit,
|
||||
onOpenReport: (String) -> Unit,
|
||||
onMore: () -> Unit,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
@@ -532,9 +579,16 @@ private fun ScheduleBody(
|
||||
}
|
||||
Text(schedule.instruction, style = MaterialTheme.typography.bodyMedium)
|
||||
val facts = listOfNotNull(
|
||||
schedule.model?.takeIf { it.isNotBlank() }?.let { stringResource(R.string.schedule_model, it) },
|
||||
stringResource(R.string.schedule_type) + ": " +
|
||||
stringResource(if (schedule.agentic) R.string.schedule_agentic else R.string.schedule_chat),
|
||||
// An Agentic schedule with no model of its own runs on the folder's usual one.
|
||||
stringResource(
|
||||
R.string.schedule_model,
|
||||
state.models.saidWithConnection(schedule.modelRef, schedule.model)
|
||||
?: stringResource(if (schedule.agentic) R.string.schedule_folder_model else R.string.schedule_first_free_model),
|
||||
),
|
||||
modeWords(schedule.mode),
|
||||
notifyWords(schedule.notify),
|
||||
notifyWords(schedule),
|
||||
)
|
||||
if (facts.isNotEmpty()) {
|
||||
Text(facts.joinToString(" · "), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
@@ -595,16 +649,29 @@ private fun ScheduleBody(
|
||||
)
|
||||
}
|
||||
}
|
||||
items(state.runs, key = { it.id }) { run -> RunRow(run, schedule.runsOn, onOpen = { onOpenRun(run) }) }
|
||||
items(state.runs, key = { it.id }) { run ->
|
||||
RunRow(run, schedule.runsOn, onOpen = { onOpenRun(run) }, onOpenReport = onOpenReport, models = state.models)
|
||||
}
|
||||
if (state.more) item { LaunchedEffect(state.runs.size) { onMore() } }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun notifyWords(notify: String): String? = when (notify) {
|
||||
private fun notifyWords(schedule: Schedule): String? = when (schedule.notify) {
|
||||
"always" -> stringResource(R.string.notify_always)
|
||||
|
||||
// "When…" with the person's own words (spec 3.8.0); a server before it said "matters".
|
||||
"when" -> stringResource(
|
||||
R.string.notify_when_words,
|
||||
schedule.notifyWhen.ifBlank {
|
||||
schedule.notifyDefault.ifBlank { stringResource(R.string.notify_when_default) }
|
||||
},
|
||||
)
|
||||
|
||||
"matters" -> stringResource(R.string.notify_matters)
|
||||
|
||||
"never" -> stringResource(R.string.notify_never)
|
||||
|
||||
else -> null
|
||||
}
|
||||
|
||||
@@ -643,6 +710,23 @@ private fun ComputerLine(on: RunsOn, away: Boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
/** A run's own line for where it ran: the computer and the folder there. The folder gives first. */
|
||||
@Composable
|
||||
private fun RanOnLine(on: RanOn) {
|
||||
val palette = LocalPalette.current
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Computer, contentDescription = stringResource(R.string.schedule_computer), tint = palette.inkFaint, modifier = Modifier.size(14.dp))
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text(
|
||||
listOf(on.deviceName.ifBlank { stringResource(R.string.schedule_computer_gone) }, on.cwd).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** A run row's line: the computer's name, and "not linked now" when the run found it away. */
|
||||
@Composable
|
||||
private fun ComputerName(on: RunsOn, away: Boolean) {
|
||||
@@ -696,7 +780,7 @@ internal fun Header(text: String) {
|
||||
* whole row opens the run.
|
||||
*/
|
||||
@Composable
|
||||
private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit) {
|
||||
private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit, onOpenReport: (String) -> Unit = {}, models: List<SchedulingModel> = emptyList()) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(
|
||||
onClick = onOpen,
|
||||
@@ -709,23 +793,46 @@ private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit) {
|
||||
Box(Modifier.width(112.dp)) { StatusChip(run.status, run.missed, run.waitingFor) }
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(ScheduleLogic.moment(run.startedAt ?: run.dueAt) ?: "—", style = MaterialTheme.typography.bodyMedium)
|
||||
// Which computer the run was for, and whether it was away.
|
||||
runsOn?.let { on -> ComputerName(on, away = run.computerAway) }
|
||||
RunFacts(run, maxLines = 2)
|
||||
// Where the run ran (its own word, spec 3.9.0), else which computer it was for --
|
||||
// and whether that was away.
|
||||
val ran = run.ranOn?.takeIf { it.device.isNotBlank() }
|
||||
when {
|
||||
ran != null -> RanOnLine(ran)
|
||||
runsOn != null -> ComputerName(runsOn, away = run.computerAway)
|
||||
}
|
||||
RunFacts(run, maxLines = 2, models = models)
|
||||
run.reportId?.let { report -> ReportLink(onClick = { onOpenReport(report) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Under a run's time: the model and why, then the result's first lines, or the trouble. */
|
||||
/** A run that filed a report: the way to it, a tap target of its own inside the run's row. */
|
||||
@Composable
|
||||
internal fun RunFacts(run: ScheduleRun, maxLines: Int = Int.MAX_VALUE, withPreview: Boolean = true) {
|
||||
internal fun ReportLink(onClick: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val name = run.model.label
|
||||
Row(
|
||||
Modifier.clip(RoundedCornerShape(12.dp)).clickable(onClick = onClick).heightIn(min = 40.dp).padding(end = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(Icons.Filled.Summarize, contentDescription = null, tint = palette.accent, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.run_open_report), style = MaterialTheme.typography.labelLarge, color = palette.accent)
|
||||
}
|
||||
}
|
||||
|
||||
/** Under a run's time: the model and why, what it is doing or the trouble, then its note (or the result's first lines). */
|
||||
@Composable
|
||||
internal fun RunFacts(run: ScheduleRun, maxLines: Int = Int.MAX_VALUE, withPreview: Boolean = true, models: List<SchedulingModel> = emptyList()) {
|
||||
val palette = LocalPalette.current
|
||||
// Which connection ran it, where the run says so and two models here share the id.
|
||||
val name = models.saidWithConnection(run.model.ref, run.model.label)
|
||||
val from = run.model.switchedFrom
|
||||
val why = runModelWhy(run.model.reason)
|
||||
val model = when {
|
||||
name == null -> null
|
||||
run.model.reason == "switched" && from != null -> stringResource(R.string.run_model_instead, name, from)
|
||||
why != null -> name + " · " + stringResource(why)
|
||||
else -> name
|
||||
}
|
||||
model?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) }
|
||||
@@ -744,11 +851,27 @@ internal fun RunFacts(run: ScheduleRun, maxLines: Int = Int.MAX_VALUE, withPrevi
|
||||
val tone = if (run.status == "waiting") palette.inkMuted else palette.danger
|
||||
Text(it, style = MaterialTheme.typography.bodySmall, color = tone, maxLines = maxLines, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
if (withPreview && run.preview.isNotBlank()) {
|
||||
// The run's own line for the history (spec 3.8.0): what it found, or why it filed no report.
|
||||
// A model's words: plain text. A server before it sends the result's first lines instead.
|
||||
if (run.note.isNotBlank()) {
|
||||
Text(run.note, style = MaterialTheme.typography.bodySmall, color = palette.ink, maxLines = maxLines, overflow = TextOverflow.Ellipsis)
|
||||
} else if (withPreview && run.preview.isNotBlank()) {
|
||||
Text(run.preview, style = MaterialTheme.typography.bodySmall, color = palette.ink, maxLines = maxLines, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How a run's model was chosen, where that is worth a word (spec 3.9.0): the folder's usual
|
||||
* one, the person's default where the folder had none, or a continued conversation's own. A
|
||||
* pinned model needs none, and a switched one has its own sentence.
|
||||
*/
|
||||
fun runModelWhy(reason: String?): Int? = when (reason) {
|
||||
"directory" -> R.string.run_model_directory
|
||||
"default" -> R.string.run_model_default
|
||||
"session" -> R.string.run_model_session
|
||||
else -> null
|
||||
}
|
||||
|
||||
// --- Create and edit ------------------------------------------------------------------------
|
||||
|
||||
data class EditState(
|
||||
@@ -758,8 +881,173 @@ data class EditState(
|
||||
val saving: Boolean = false,
|
||||
val error: String? = null,
|
||||
val unsupported: Boolean = false,
|
||||
/** Notify when (spec 3.8.0): `always`, `when` or `never`, and the person's words for `when` (empty: the default). */
|
||||
val notify: String = "when",
|
||||
val notifyWhen: String = "",
|
||||
/** Whether the instance has Reports (LLeMbas 2.0.0-beta.12): an older one is neither shown nor sent "notify when". */
|
||||
val reports: Boolean = false,
|
||||
/** The server's default condition in the account's language, when it said one. */
|
||||
val notifyDefault: String = "",
|
||||
/** Editing: the schedule was read, so the form shows what it really has; or reading it failed, and nothing may be saved over it. */
|
||||
val loaded: Boolean = false,
|
||||
val loadFailed: Boolean = false,
|
||||
/** The person chose a "notify when" themselves. */
|
||||
val notifyTouched: Boolean = false,
|
||||
/** The type (spec 3.9.0): Agentic runs on [device], in [cwd]; Chat on the server. */
|
||||
val agentic: Boolean = false,
|
||||
/** The linked computers, and -- for a schedule being edited -- its own, linked now or not. */
|
||||
val devices: List<LinkedDevice> = emptyList(),
|
||||
val device: String = "",
|
||||
val cwd: String = "",
|
||||
/** The agent's mode on the computer: `manual`, `edit` or `auto`. */
|
||||
val agentMode: String = "edit",
|
||||
/** How long an approval waits, in minutes, as typed; empty: the instance's own. */
|
||||
val wait: String = "",
|
||||
/** An Agentic schedule's model; empty: the folder's usual model. */
|
||||
val model: String = "",
|
||||
/** [model] is the schedule's own `model_ref` as read: looked up as a ref alone ([modelInfo]). A pick is not. */
|
||||
val modelIsRef: Boolean = false,
|
||||
/** The models scheduled work may run on (`GET /schedules/models`): never an interactive-only one. */
|
||||
val models: List<SchedulingModel> = emptyList(),
|
||||
/** The person changed the type or one of its fields themselves. */
|
||||
val whereTouched: Boolean = false,
|
||||
/** What the schedule being edited was when it was read: Agentic or Chat. */
|
||||
val wasAgentic: Boolean = false,
|
||||
/** Where the schedule being edited ran, its model and its watched command, as they were read: a save says only what differs. */
|
||||
val readWhere: WhereToRun.Computer? = null,
|
||||
val readModel: String = "",
|
||||
val readWatch: WatchCommand = WatchCommand("", null),
|
||||
/** An Agentic schedule's watched command (empty: none), and the seconds it may take, as typed. */
|
||||
val watchCommand: String = "",
|
||||
val watchTimeout: String = "",
|
||||
)
|
||||
|
||||
/** The agent modes, narrowest first. */
|
||||
val AGENT_MODES = listOf("manual", "edit", "auto")
|
||||
|
||||
/**
|
||||
* The modes the form offers for a computer whose widest is [maxMode]: none wider than it
|
||||
* (every one where it names none, as an older computer does), and the mode the schedule
|
||||
* already has ([current]) whatever the computer says now -- it lowers it itself.
|
||||
*/
|
||||
fun modesOffered(maxMode: String, current: String): List<String> {
|
||||
val widest = AGENT_MODES.indexOf(maxMode).takeIf { it >= 0 } ?: AGENT_MODES.lastIndex
|
||||
return AGENT_MODES.filterIndexed { i, mode -> i <= widest || mode == current }
|
||||
}
|
||||
|
||||
/** Where the form says the schedule runs, as a save would say it. */
|
||||
val EditState.computer: WhereToRun.Computer get() = WhereToRun.Computer(device, cwd.trim(), agentMode, waitMinutes)
|
||||
|
||||
/** The watched command as the form holds it: the seconds only between 1 and 600, and only with a command. */
|
||||
val EditState.watched: WatchCommand
|
||||
get() = watchCommand.trim().let { command -> WatchCommand(command, watchTimeout.trim().toIntOrNull()?.takeIf { command.isNotEmpty() && it in 1..600 }) }
|
||||
|
||||
/** An Agentic schedule that watches a command is being made a Chat one: the command cannot go with it. */
|
||||
val EditState.dropsWatch: Boolean get() = !agentic && wasAgentic && readWatch.command.isNotEmpty()
|
||||
|
||||
/** Agentic is offered only while one of the person's computers accepts scheduled work. */
|
||||
val EditState.agenticOffered: Boolean get() = devices.any { it.scheduled }
|
||||
|
||||
/** The computer chosen, when it is one of those listed. */
|
||||
val EditState.chosenDevice: LinkedDevice? get() = devices.firstOrNull { it.id == device }
|
||||
|
||||
/** An approval's wait as a number of minutes, or null for the instance's own (empty, or not a number). */
|
||||
val EditState.waitMinutes: Int? get() = wait.trim().toIntOrNull()?.takeIf { it > 0 }
|
||||
|
||||
/** What an Agentic schedule still lacks before it can be saved: a computer and a full path. */
|
||||
val EditState.whereComplete: Boolean get() = !agentic || (device.isNotBlank() && cwd.isNotBlank())
|
||||
|
||||
/**
|
||||
* Where a save says the schedule runs -- its type. A new schedule says a computer when it is
|
||||
* Agentic and nothing otherwise (the server's own default is Chat). An edit says only what
|
||||
* the form knows and what differs from what it read: nothing where the schedule could not be
|
||||
* read, nothing for a schedule whose computer, folder, mode and wait are as they were (so its
|
||||
* words can be put right while its computer is not linked), and "the server" only when an
|
||||
* Agentic schedule was made a Chat one.
|
||||
*/
|
||||
fun whereToSend(state: EditState, editing: Boolean): WhereToRun = when {
|
||||
editing && !state.loaded -> WhereToRun.Leave
|
||||
state.agentic -> state.computer.takeUnless { editing && it == state.readWhere } ?: WhereToRun.Leave
|
||||
editing && state.wasAgentic -> WhereToRun.Server
|
||||
else -> WhereToRun.Leave
|
||||
}
|
||||
|
||||
/**
|
||||
* The model a save says, or null for none: an Agentic schedule's, when it is new and one was
|
||||
* chosen, or when it differs from the one read (the empty one is then said too: back to the
|
||||
* folder's usual model). A Chat schedule's model is not this form's to change.
|
||||
*/
|
||||
fun modelToSend(state: EditState, editing: Boolean): String? = when {
|
||||
!state.agentic || (editing && !state.loaded) -> null
|
||||
editing -> state.model.takeIf { it != state.readModel }
|
||||
else -> state.model.ifBlank { null }
|
||||
}
|
||||
|
||||
/**
|
||||
* The watched command a save says, or null for none: an Agentic schedule's when it differs
|
||||
* from the one read (an emptied field is said: watch nothing), a new one's when one was
|
||||
* written -- and "watch nothing" for a schedule made Chat that watched a command, which the
|
||||
* server would otherwise refuse.
|
||||
*/
|
||||
fun watchToSend(state: EditState, editing: Boolean): WatchCommand? = when {
|
||||
editing && !state.loaded -> null
|
||||
state.agentic -> state.watched.takeIf { if (editing) it != state.readWatch else it.command.isNotEmpty() }
|
||||
state.dropsWatch -> WatchCommand("", null)
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** The form's model among the models offered: by its ref alone where the schedule itself said one. */
|
||||
val EditState.modelInfo: SchedulingModel? get() = models.named(model, modelIsRef)
|
||||
|
||||
/** A schedule as the form holds where it runs; what the person changed meanwhile stays changed. */
|
||||
fun EditState.read(s: Schedule): EditState {
|
||||
val on = s.runsOn
|
||||
val known = devices.any { it.id == on?.device }
|
||||
val watch = s.watch?.takeIf { it.kind == "command" }?.let { WatchCommand(it.command.ifBlank { it.target }.trim(), it.timeoutS) } ?: WatchCommand("", null)
|
||||
return copy(
|
||||
wasAgentic = on != null,
|
||||
readWhere = on?.let {
|
||||
WhereToRun.Computer(it.device, it.cwd.trim(), it.mode.ifBlank { "edit" }, it.approvalWaitMinutes?.takeIf { minutes -> minutes > 0 })
|
||||
},
|
||||
readModel = s.modelKey.orEmpty(),
|
||||
readWatch = watch,
|
||||
// Its own computer is in the list also when it is not linked now, so it can stay chosen.
|
||||
devices = if (on == null || known) devices else devices + LinkedDevice(id = on.device, name = on.deviceName),
|
||||
agentic = if (whereTouched) agentic else on != null,
|
||||
device = if (whereTouched || on == null) device else on.device,
|
||||
cwd = if (whereTouched || on == null) cwd else on.cwd,
|
||||
agentMode = if (whereTouched || on == null) agentMode else on.mode.ifBlank { agentMode },
|
||||
wait = if (whereTouched || on == null) wait else on.approvalWaitMinutes?.toString().orEmpty(),
|
||||
// A Chat schedule's own model too: made Agentic, it is shown as the model it keeps.
|
||||
// By its connection where the server says it: the form then ticks the right one of two with one id.
|
||||
model = if (whereTouched) model else s.modelKey.orEmpty(),
|
||||
modelIsRef = if (whereTouched) modelIsRef else !s.modelRef.isNullOrBlank(),
|
||||
watchCommand = if (whereTouched) watchCommand else watch.command,
|
||||
watchTimeout = if (whereTouched) watchTimeout else watch.timeoutS?.toString().orEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
/** The linked computers as the form lists them, keeping a schedule's own that is not among them. */
|
||||
fun EditState.listed(linked: List<LinkedDevice>): EditState {
|
||||
val own = devices.filter { mine -> linked.none { it.id == mine.id } && mine.id == device }
|
||||
val all = linked + own
|
||||
// A new Agentic schedule starts on the first computer that accepts scheduled work.
|
||||
return copy(devices = all, device = device.ifBlank { all.firstOrNull { it.scheduled }?.id.orEmpty() })
|
||||
}
|
||||
|
||||
/**
|
||||
* The `notify` a save sends, or null for none: only to an instance with Reports, and when
|
||||
* [editing] only what the form really knows -- the schedule's own value once it was read, or the
|
||||
* person's choice. A form that could not read the schedule must not write its default over an
|
||||
* "every run" or a "never".
|
||||
*/
|
||||
fun notifyToSend(state: EditState, editing: Boolean): String? = when {
|
||||
!state.reports -> null
|
||||
!editing -> state.notify
|
||||
state.loaded || state.notifyTouched -> state.notify
|
||||
else -> null
|
||||
}
|
||||
|
||||
class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(EditState())
|
||||
val state = _state.asStateFlow()
|
||||
@@ -771,16 +1059,55 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
|
||||
if (started) return
|
||||
started = true
|
||||
editing = id
|
||||
// "Notify when" belongs to an instance that files reports; one that has no such route
|
||||
// would refuse the new values, so it is asked first.
|
||||
viewModelScope.launch {
|
||||
val has = runCatching { getApplication<Application>().api().reports(unread = true) }.isSuccess
|
||||
_state.update { it.copy(reports = has) }
|
||||
}
|
||||
// The type's choices: the computers (Agentic is offered while one accepts scheduled
|
||||
// work) and the models a schedule may run on. Either may be missing on an older server.
|
||||
viewModelScope.launch {
|
||||
runCatching { getApplication<Application>().api().devices() }.onSuccess { linked -> _state.update { it.listed(linked) } }
|
||||
}
|
||||
viewModelScope.launch {
|
||||
runCatching { getApplication<Application>().api().schedulingModels() }.onSuccess { m -> _state.update { it.copy(models = m.models) } }
|
||||
}
|
||||
if (id == null) return
|
||||
viewModelScope.launch {
|
||||
runCatching { getApplication<Application>().api().schedule(id) }.onSuccess { s ->
|
||||
_state.update { it.copy(words = s.request.ifBlank { s.instruction }) }
|
||||
_state.update {
|
||||
it.read(s).copy(
|
||||
words = s.request.ifBlank { s.instruction },
|
||||
// What the person chose while it was read stays chosen.
|
||||
notify = if (it.notifyTouched) it.notify else notifyChoice(s.notify),
|
||||
notifyWhen = if (it.notifyTouched) it.notifyWhen else s.notifyWhen,
|
||||
notifyDefault = s.notifyDefault,
|
||||
loaded = true,
|
||||
)
|
||||
}
|
||||
}.onFailure { e ->
|
||||
// Not read: said, and Save waits -- the form would write its own defaults over the schedule.
|
||||
_state.update { it.copy(loadFailed = true, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun words(text: String) = _state.update { it.copy(words = text, compiled = null) }
|
||||
|
||||
fun notify(value: String) = _state.update { it.copy(notify = notifyChoice(value), notifyTouched = true) }
|
||||
|
||||
fun notifyWhen(text: String) = _state.update { it.copy(notifyWhen = text, notifyTouched = true) }
|
||||
|
||||
/** A change to the type or one of its fields: the person's, so a schedule read later does not undo it. */
|
||||
fun where(change: (EditState) -> EditState) = _state.update { change(it).copy(whereTouched = true, error = null) }
|
||||
|
||||
/** The chosen computer, asked for a directory (`""`: its places), for the folder picker. */
|
||||
suspend fun directories(path: String): DeviceDirectory {
|
||||
val device = _state.value.device.ifBlank { return DeviceDirectory(code = "device_not_linked") }
|
||||
return getApplication<Application>().api().deviceDirectories(device, path)
|
||||
}
|
||||
|
||||
/** The server reads the words: the title, the instruction, the rule and the next runs. */
|
||||
fun preview() {
|
||||
val words = _state.value.words.trim()
|
||||
@@ -803,7 +1130,17 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(saving = true, error = null) }
|
||||
try {
|
||||
val saved = getApplication<Application>().api().saveSchedule(compiled, _state.value.words.trim(), editing)
|
||||
val now = _state.value
|
||||
val saved = getApplication<Application>().api().saveSchedule(
|
||||
compiled,
|
||||
now.words.trim(),
|
||||
editing,
|
||||
notify = notifyToSend(now, editing = editing != null),
|
||||
notifyWhen = now.notifyWhen,
|
||||
where = whereToSend(now, editing = editing != null),
|
||||
model = modelToSend(now, editing = editing != null),
|
||||
watch = watchToSend(now, editing = editing != null),
|
||||
)
|
||||
then(saved.id)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(saving = false, error = getApplication<Application>().explain(e)) }
|
||||
@@ -821,7 +1158,18 @@ fun ScheduleEditScreen(
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(id) { model.start(id) }
|
||||
ScheduleEditContent(state, editing = id != null, onBack = onBack, onWords = model::words, onPreview = model::preview, onSave = { model.save(onSaved) })
|
||||
ScheduleEditContent(
|
||||
state,
|
||||
editing = id != null,
|
||||
onBack = onBack,
|
||||
onWords = model::words,
|
||||
onPreview = model::preview,
|
||||
onSave = { model.save(onSaved) },
|
||||
onNotify = model::notify,
|
||||
onNotifyWhen = model::notifyWhen,
|
||||
onWhere = model::where,
|
||||
directories = model::directories,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -838,6 +1186,10 @@ fun ScheduleEditContent(
|
||||
onWords: (String) -> Unit = {},
|
||||
onPreview: () -> Unit = {},
|
||||
onSave: () -> Unit = {},
|
||||
onNotify: (String) -> Unit = {},
|
||||
onNotifyWhen: (String) -> Unit = {},
|
||||
onWhere: ((EditState) -> EditState) -> Unit = {},
|
||||
directories: suspend (String) -> DeviceDirectory = { DeviceDirectory() },
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Scaffold(
|
||||
@@ -847,7 +1199,7 @@ fun ScheduleEditContent(
|
||||
Box(Modifier.background(palette.bg).navigationBarsPadding().imePadding().padding(16.dp)) {
|
||||
Button(
|
||||
onClick = onSave,
|
||||
enabled = state.compiled?.savable == true && !state.saving,
|
||||
enabled = state.compiled?.savable == true && !state.saving && !state.loadFailed && state.whereComplete,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
|
||||
) { Text(stringResource(R.string.save)) }
|
||||
}
|
||||
@@ -857,6 +1209,10 @@ fun ScheduleEditContent(
|
||||
Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
// The type comes first: it decides where the task runs and what else the form asks.
|
||||
// Not until a schedule being edited has been read: a choice made before would be the form's guess.
|
||||
TypeChoice(state, onWhere, ready = !editing || state.loaded)
|
||||
if (state.agentic) OnComputer(state, onWhere, directories)
|
||||
Text(stringResource(R.string.schedule_words_hint), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
OutlinedTextField(
|
||||
value = state.words,
|
||||
@@ -880,11 +1236,297 @@ fun ScheduleEditContent(
|
||||
if (state.unsupported) Text(stringResource(R.string.scheduled_unsupported), color = palette.inkMuted)
|
||||
state.error?.let { Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium) }
|
||||
state.compiled?.let { Understood(it) }
|
||||
if (state.reports) NotifyWhen(state.notify, state.notifyWhen, state.notifyDefault, onNotify, onNotifyWhen)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The type (spec 3.9.0): Chat runs on the server, Agentic on one of the person's computers, each
|
||||
* with one line saying what that means. Agentic cannot be chosen while no computer accepts
|
||||
* scheduled work, and says so; one that is Agentic already stays shown as it is.
|
||||
*/
|
||||
@Composable
|
||||
private fun TypeChoice(state: EditState, onWhere: ((EditState) -> EditState) -> Unit, ready: Boolean = true) {
|
||||
val palette = LocalPalette.current
|
||||
val offered = ready && (state.agenticOffered || state.agentic)
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(vertical = 12.dp)) {
|
||||
Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
stringResource(R.string.schedule_type),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = palette.accent,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// The schedule is still being read: its type is not known yet, and not to be chosen.
|
||||
// (Not in a preview or a screenshot: an animation that never ends never lets the picture be taken.)
|
||||
if (!ready && !state.loadFailed && !LocalInspectionMode.current) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(16.dp))
|
||||
}
|
||||
ChoiceRow(
|
||||
selected = ready && !state.agentic,
|
||||
enabled = ready,
|
||||
title = stringResource(R.string.schedule_chat),
|
||||
line = stringResource(R.string.schedule_chat_line),
|
||||
onClick = { onWhere { it.copy(agentic = false) } },
|
||||
)
|
||||
ChoiceRow(
|
||||
selected = ready && state.agentic,
|
||||
enabled = offered,
|
||||
title = stringResource(R.string.schedule_agentic),
|
||||
line = stringResource(if (offered || !ready) R.string.schedule_agentic_line else R.string.schedule_agentic_unavailable),
|
||||
onClick = { onWhere { it.copy(agentic = true) } },
|
||||
)
|
||||
if (state.dropsWatch) {
|
||||
Text(
|
||||
stringResource(R.string.schedule_chat_drops_watch),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.warning,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One choice of a few: the radio button keeps its size, the words give. The whole row is the target. */
|
||||
@Composable
|
||||
private fun ChoiceRow(selected: Boolean, title: String, line: String?, onClick: () -> Unit, enabled: Boolean = true) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable(
|
||||
enabled = enabled,
|
||||
onClick = onClick,
|
||||
).heightIn(min = 56.dp).padding(start = 4.dp, end = 16.dp, top = 4.dp, bottom = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(selected = selected, onClick = onClick, enabled = enabled)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge, color = if (enabled) palette.ink else palette.inkFaint)
|
||||
line?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An Agentic schedule's own fields: the computer, the folder there (the picker, or a typed
|
||||
* path), the mode, how long an approval waits, and the model -- the folder's usual one unless
|
||||
* another is chosen.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun OnComputer(state: EditState, onWhere: ((EditState) -> EditState) -> Unit, directories: suspend (String) -> DeviceDirectory) {
|
||||
val palette = LocalPalette.current
|
||||
var browsing by remember { mutableStateOf(false) }
|
||||
var choosingModel by remember { mutableStateOf(false) }
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(vertical = 12.dp)) {
|
||||
FieldLabel(stringResource(R.string.schedule_computer))
|
||||
state.devices.forEach { d ->
|
||||
// A computer that does not accept scheduled work cannot be chosen; the one the
|
||||
// schedule already has stays shown, whatever it says now.
|
||||
val mine = d.id == state.device
|
||||
ChoiceRow(
|
||||
selected = mine,
|
||||
enabled = d.scheduled || mine,
|
||||
title = d.label,
|
||||
line = if (d.scheduled) null else stringResource(R.string.schedule_computer_refuses),
|
||||
onClick = { onWhere { it.copy(device = d.id) } },
|
||||
)
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.schedule_computer_hint),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(horizontal = 16.dp),
|
||||
)
|
||||
|
||||
FieldLabel(stringResource(R.string.schedule_folder))
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = state.cwd,
|
||||
onValueChange = { text -> onWhere { it.copy(cwd = text) } },
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.directory_path)) },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
IconButton(onClick = { browsing = true }, enabled = state.device.isNotBlank()) {
|
||||
Icon(Icons.Filled.Folder, contentDescription = stringResource(R.string.directory_browse), tint = palette.accent)
|
||||
}
|
||||
}
|
||||
|
||||
FieldLabel(stringResource(R.string.schedule_agent_mode))
|
||||
FlowRow(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
// Only the modes the chosen computer allows, and the one the schedule has.
|
||||
modesOffered(state.chosenDevice?.maxMode.orEmpty(), state.agentMode).forEach { value ->
|
||||
FilterChip(
|
||||
selected = state.agentMode == value,
|
||||
onClick = { onWhere { it.copy(agentMode = value) } },
|
||||
label = { Text(agentModeWords(value) ?: value) },
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.schedule_agent_mode_hint),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(horizontal = 16.dp),
|
||||
)
|
||||
|
||||
FieldLabel(stringResource(R.string.schedule_approval_wait))
|
||||
OutlinedTextField(
|
||||
value = state.wait,
|
||||
onValueChange = { text -> onWhere { it.copy(wait = text.filter(Char::isDigit).take(4)) } },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
supportingText = { Text(stringResource(R.string.schedule_approval_wait_hint)) },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
)
|
||||
|
||||
FieldLabel(stringResource(R.string.schedule_watching_command))
|
||||
OutlinedTextField(
|
||||
value = state.watchCommand,
|
||||
onValueChange = { text -> onWhere { it.copy(watchCommand = text.take(1000)) } },
|
||||
singleLine = true,
|
||||
supportingText = { Text(stringResource(R.string.schedule_watch_command_hint)) },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
)
|
||||
if (state.watchCommand.isNotBlank()) {
|
||||
FieldLabel(stringResource(R.string.schedule_watch_timeout))
|
||||
OutlinedTextField(
|
||||
value = state.watchTimeout,
|
||||
onValueChange = { text -> onWhere { it.copy(watchTimeout = text.filter(Char::isDigit).take(3)) } },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
supportingText = { Text(stringResource(R.string.schedule_watch_timeout_hint)) },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
)
|
||||
}
|
||||
|
||||
FieldLabel(stringResource(R.string.model))
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { choosingModel = true }.heightIn(min = 56.dp).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
state.modelInfo?.titleAmong(state.models)
|
||||
?: state.model.ifBlank { stringResource(R.string.schedule_folder_model) },
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
)
|
||||
Text(stringResource(R.string.schedule_folder_model_hint), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Icon(Icons.Filled.Tune, contentDescription = null, tint = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (browsing) {
|
||||
DirectoryPicker(
|
||||
title = state.chosenDevice?.label ?: stringResource(R.string.schedule_folder),
|
||||
initial = state.cwd,
|
||||
load = directories,
|
||||
onPick = { path ->
|
||||
onWhere { it.copy(cwd = path) }
|
||||
browsing = false
|
||||
},
|
||||
onDismiss = { browsing = false },
|
||||
)
|
||||
}
|
||||
if (choosingModel) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { choosingModel = false },
|
||||
title = { Text(stringResource(R.string.model)) },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
// A row of the list is picked by its key; the schedule's own model stays the ref it was read as.
|
||||
val pick: (String, Boolean) -> Unit = { id, isRef ->
|
||||
onWhere { it.copy(model = id, modelIsRef = isRef) }
|
||||
choosingModel = false
|
||||
}
|
||||
ChoiceRow(selected = state.model.isBlank(), title = stringResource(R.string.schedule_folder_model), line = null, onClick = {
|
||||
pick("", false)
|
||||
})
|
||||
// The schedule's own model stays offered where the instance no longer lists it: the server says why on Save.
|
||||
val own = state.model.takeIf { m -> m.isNotBlank() && state.modelInfo == null }
|
||||
own?.let { ChoiceRow(selected = true, title = it, line = null, onClick = { pick(it, state.modelIsRef) }) }
|
||||
// A schedule that says its connection ticks that row or none; one that says only an id, the first with it.
|
||||
val chosen = state.modelInfo?.key
|
||||
state.models.distinctBy { it.key }.forEach { m ->
|
||||
ChoiceRow(selected = chosen == m.key, title = m.titleAmong(state.models), line = null, onClick = { pick(m.key, false) })
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { choosingModel = false }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FieldLabel(text: String) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = LocalPalette.current.accent,
|
||||
modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify when: every run, when the person's own words hold, or never -- each with one line
|
||||
* saying what it does. A report is what tells the person; a run without one is a line in the
|
||||
* task's history. "When…" opens a field with the default already in it.
|
||||
*/
|
||||
@Composable
|
||||
private fun NotifyWhen(notify: String, words: String, default: String, onNotify: (String) -> Unit, onWords: (String) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val choices = listOf(
|
||||
Triple("always", R.string.notify_every_run, R.string.notify_every_run_line),
|
||||
Triple("when", R.string.notify_when_option, R.string.notify_when_line),
|
||||
Triple("never", R.string.notify_never_option, R.string.notify_never_line),
|
||||
)
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(vertical = 12.dp)) {
|
||||
Text(
|
||||
stringResource(R.string.notify_when),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = palette.accent,
|
||||
modifier = Modifier.padding(horizontal = 16.dp),
|
||||
)
|
||||
choices.forEach { (value, title, line) ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { onNotify(value) }.heightIn(min = 56.dp).padding(start = 4.dp, end = 16.dp, top = 4.dp, bottom = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(selected = notify == value, onClick = { onNotify(value) })
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(title), style = MaterialTheme.typography.bodyLarge)
|
||||
Text(stringResource(line), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
if (value == "when" && notify == "when") {
|
||||
val usual = default.ifBlank { stringResource(R.string.notify_when_default) }
|
||||
OutlinedTextField(
|
||||
// Empty is allowed and means the default, which stands there as the placeholder.
|
||||
value = words,
|
||||
onValueChange = onWords,
|
||||
label = { Text(stringResource(R.string.notify_when_label)) },
|
||||
placeholder = { Text(usual) },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 52.dp, end = 16.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What the server made of the words. The title and instruction are a model's: plain text. */
|
||||
@Composable
|
||||
private fun Understood(c: ScheduleCompiled) {
|
||||
|
||||
@@ -133,7 +133,7 @@ fun SchedulingModelsContent(state: ModelsState, onBack: () -> Unit = {}, onToggl
|
||||
)
|
||||
}
|
||||
state.error?.let { item { Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium) } }
|
||||
items(models, key = { it.id }) { m -> ModelRow(m, onToggle = { onToggle(m) }) }
|
||||
items(models.distinctBy { it.key }, key = { it.key }) { m -> ModelRow(m, onToggle = { onToggle(m) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.settings
|
||||
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LifecycleEventEffect
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.McpServer
|
||||
import eu.llembas.android.api.signInAddress
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.files.filesSay
|
||||
import eu.llembas.android.ui.scheduled.ScheduleLogic
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.openOutside
|
||||
import kotlinx.coroutines.CancellationException
|
||||
|
||||
/** The instance's MCP servers as the page draws them: on their way, refused, or the list. */
|
||||
data class McpState(val servers: List<McpServer> = emptyList(), val loading: Boolean = true, val error: String? = null)
|
||||
|
||||
/**
|
||||
* Settings › MCP servers: the servers whose tools the person's chats may be offered, and how
|
||||
* each is signed in to. One that waits for a sign-in has a button that opens the instance's own
|
||||
* sign-in page **in the browser** -- the sign-in happens there, against the instance, with the
|
||||
* person signed in to the instance by its cookie. The app starts and finishes nothing, and sees,
|
||||
* sends and stores no token of a server; its own token is in no address it opens. The list is
|
||||
* read again whenever the page comes back to the front, which is when the browser was left.
|
||||
*/
|
||||
@Composable
|
||||
fun McpScreen(onBack: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
var state by remember { mutableStateOf(McpState()) }
|
||||
var reads by remember { mutableIntStateOf(0) }
|
||||
var base by remember { mutableStateOf("") }
|
||||
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { reads++ }
|
||||
LaunchedEffect(reads) {
|
||||
state = state.copy(loading = true, error = null)
|
||||
state = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
base = api.base
|
||||
McpState(api.mcpServers(), loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state.copy(loading = false, error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
McpContent(
|
||||
state,
|
||||
onBack = onBack,
|
||||
onReload = { reads++ },
|
||||
// Only a page of the instance the app is signed in to is ever opened (signInAddress).
|
||||
onSignIn = { server -> signInAddress(base, server.auth.signinUrl)?.let { openOutside(context, it) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** The words for how a server is signed in to; a state this app does not know is said as the instance says it. */
|
||||
@Composable
|
||||
internal fun mcpState(server: McpServer): String = when (server.auth.state) {
|
||||
"ready" -> stringResource(R.string.mcp_ready)
|
||||
"signed_in" -> stringResource(R.string.mcp_signed_in)
|
||||
"signed_out" -> stringResource(R.string.mcp_signed_out)
|
||||
"needs_signin" -> stringResource(R.string.mcp_needs_signin)
|
||||
else -> server.auth.state
|
||||
}
|
||||
|
||||
/** The page, from [state] alone. Each server is a card: its words stacked, and under them the one button, the card's whole width. */
|
||||
@Composable
|
||||
fun McpContent(state: McpState, onBack: () -> Unit = {}, onReload: () -> Unit = {}, onSignIn: (McpServer) -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg, scrolledContainerColor = palette.bg),
|
||||
title = { Text(stringResource(R.string.mcp_title), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
},
|
||||
actions = { IconButton(onClick = onReload) { Icon(Icons.Filled.Refresh, contentDescription = stringResource(R.string.reload)) } },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when {
|
||||
state.error != null -> Text(state.error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
|
||||
state.loading && state.servers.isEmpty() -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
|
||||
state.servers.isEmpty() -> Text(
|
||||
stringResource(R.string.mcp_none),
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.align(Alignment.Center).padding(32.dp),
|
||||
)
|
||||
|
||||
else -> LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
item { Text(stringResource(R.string.mcp_intro), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) }
|
||||
items(state.servers, key = { it.id }) { server -> McpCard(server, onSignIn) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun McpCard(server: McpServer, onSignIn: (McpServer) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val auth = server.auth
|
||||
Column(
|
||||
Modifier.fillMaxWidth().border(1.dp, palette.border, RoundedCornerShape(16.dp)).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Text(server.label, style = MaterialTheme.typography.titleMedium, color = palette.ink)
|
||||
Text(
|
||||
listOf(mcpState(server), stringResource(R.string.mcp_tools, server.tools.toString())).joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (auth.needsSignIn) palette.danger else palette.inkMuted,
|
||||
)
|
||||
// Who the provider says signed in: a stranger's text, drawn as plain text.
|
||||
if (auth.account.isNotBlank()) {
|
||||
Text(stringResource(R.string.mcp_account, auth.account), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
if (!auth.needsSignIn) {
|
||||
ScheduleLogic.moment(auth.expiresAt)?.let {
|
||||
Text(stringResource(R.string.mcp_until, it), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
if (auth.needsSignIn) {
|
||||
if (auth.signinUrl.isNullOrBlank()) {
|
||||
// One sign-in for everyone, which only an administrator makes: nothing for this person to do.
|
||||
Text(stringResource(R.string.mcp_shared_note), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
} else {
|
||||
Text(stringResource(R.string.mcp_browser_note), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
Button(
|
||||
onClick = { onSignIn(server) },
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).heightIn(min = 48.dp),
|
||||
) { Text(stringResource(R.string.mcp_sign_in)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,14 @@
|
||||
|
||||
package eu.llembas.android.ui.settings
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.SystemClock
|
||||
import android.provider.Settings
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -26,20 +31,33 @@ import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.Logout
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Assistant
|
||||
import androidx.compose.material.icons.filled.BatteryAlert
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Dns
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.Extension
|
||||
import androidx.compose.material.icons.filled.Forum
|
||||
import androidx.compose.material.icons.filled.GraphicEq
|
||||
import androidx.compose.material.icons.filled.Hearing
|
||||
import androidx.compose.material.icons.filled.History
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.MyLocation
|
||||
import androidx.compose.material.icons.filled.Navigation
|
||||
import androidx.compose.material.icons.filled.Notifications
|
||||
import androidx.compose.material.icons.filled.NotificationsActive
|
||||
import androidx.compose.material.icons.filled.Palette
|
||||
import androidx.compose.material.icons.filled.PhoneAndroid
|
||||
import androidx.compose.material.icons.filled.Psychology
|
||||
import androidx.compose.material.icons.filled.RecordVoiceOver
|
||||
import androidx.compose.material.icons.filled.Science
|
||||
import androidx.compose.material.icons.filled.ScreenLockPortrait
|
||||
import androidx.compose.material.icons.filled.Security
|
||||
import androidx.compose.material.icons.filled.SystemUpdate
|
||||
import androidx.compose.material.icons.filled.Timer
|
||||
import androidx.compose.material.icons.filled.Translate
|
||||
import androidx.compose.material.icons.filled.Tune
|
||||
import androidx.compose.material.icons.filled.Update
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -55,6 +73,7 @@ import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -71,14 +90,22 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.actions.NavApp
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.api.titleAmong
|
||||
import eu.llembas.android.assist.LembasAssistService
|
||||
import eu.llembas.android.assist.PhoneRecognizer
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.notify.NotificationAccess
|
||||
import eu.llembas.android.push.Push
|
||||
import eu.llembas.android.ui.files.FileCache
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.update.AppVersion
|
||||
import eu.llembas.android.update.ReleaseCheck
|
||||
@@ -87,12 +114,31 @@ import eu.llembas.android.update.UpdateResult
|
||||
import eu.llembas.android.update.Updater
|
||||
import eu.llembas.android.update.checksUpdates
|
||||
import eu.llembas.android.update.offersBetas
|
||||
import eu.llembas.android.wake.AssistLink
|
||||
import eu.llembas.android.wake.WakeAttempt
|
||||
import eu.llembas.android.wake.WakeEngine
|
||||
import eu.llembas.android.wake.WakeFailure
|
||||
import eu.llembas.android.wake.WakePause
|
||||
import eu.llembas.android.wake.WakePhrase
|
||||
import eu.llembas.android.wake.WakePhrases
|
||||
import eu.llembas.android.wake.WakeSensitivity
|
||||
import eu.llembas.android.wake.WakeState
|
||||
import eu.llembas.android.wake.WakeStatus
|
||||
import eu.llembas.android.wake.WakeWordService
|
||||
import eu.llembas.android.wake.WakeWords
|
||||
import eu.llembas.android.wake.wakeAttemptWords
|
||||
import eu.llembas.android.wake.wakeTitle
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** What the settings page does; every action has a do-nothing default for the screenshots. */
|
||||
interface SettingsActions {
|
||||
fun use(instance: Instance) {}
|
||||
fun add() {}
|
||||
|
||||
/** The instance's MCP servers and their sign-ins. */
|
||||
fun mcpServers() {}
|
||||
fun signOut(instance: Instance) {}
|
||||
fun theme(value: String) {}
|
||||
fun language(value: String) {}
|
||||
@@ -100,8 +146,21 @@ interface SettingsActions {
|
||||
fun notificationSettings() {}
|
||||
fun assistantSettings() {}
|
||||
fun assistantTemporary(on: Boolean) {}
|
||||
fun assistantModel(id: String) {}
|
||||
fun voiceInput(value: String) {}
|
||||
fun assistantListens(on: Boolean) {}
|
||||
fun assistantConversation(on: Boolean) {}
|
||||
fun wakeWord(on: Boolean) {}
|
||||
fun wakePhrase(id: String) {}
|
||||
fun wakeSensitivity(id: String) {}
|
||||
fun wakeTest() {}
|
||||
fun wakeRetry() {}
|
||||
fun wakeScreenOnly(on: Boolean) {}
|
||||
fun batterySettings() {}
|
||||
fun notificationSummaries(on: Boolean) {}
|
||||
fun notificationAccess() {}
|
||||
fun navApp(id: String) {}
|
||||
fun osmandInfo(on: Boolean) {}
|
||||
fun readAloud(on: Boolean) {}
|
||||
fun checkUpdate() {}
|
||||
fun openRelease() {}
|
||||
@@ -110,6 +169,9 @@ interface SettingsActions {
|
||||
fun updateBetas(on: Boolean) {}
|
||||
}
|
||||
|
||||
/** "Test the wake word" as the row shows it: not started, [running], or [done] -- with how often it was [heard]. */
|
||||
data class WakeTestShown(val running: Boolean = false, val done: Boolean = false, val heard: Int = 0)
|
||||
|
||||
/** What the settings page shows. */
|
||||
data class SettingsState(
|
||||
val instances: List<Instance> = emptyList(),
|
||||
@@ -126,34 +188,96 @@ data class SettingsState(
|
||||
val beta: Boolean = false,
|
||||
/** Whether the phone has a speech recogniser of its own (Settings › Voice input › Phone). */
|
||||
val phoneRecognizer: Boolean = false,
|
||||
/** Whether this build has a wake-word engine (the F-Droid build has none). */
|
||||
val wakeAvailable: Boolean = false,
|
||||
/** What the wake word is doing right now (WakeStatus), said under its switch while it is on. */
|
||||
val wakeState: WakeState = WakeState.Off,
|
||||
/** "Test the wake word": whether its ten seconds are running, and how often the phrase landed. */
|
||||
val wakeTest: WakeTestShown = WakeTestShown(),
|
||||
/** Whether LLeMbas is the phone's digital assistant app: only then can the wake word open it over other apps. */
|
||||
val isAssistant: Boolean = true,
|
||||
/** Whether Android has the assistant service connected right now: without it the wake word cannot open the sheet by itself. */
|
||||
val assistantConnected: Boolean = true,
|
||||
/** Whether Android itself uses LLeMbas's service as its voice assistant (the role can be held without it). */
|
||||
val assistantActive: Boolean = true,
|
||||
/** Whether Android's notification access is given to LLeMbas. */
|
||||
val notificationAccess: Boolean = false,
|
||||
/** Whether this build can read notifications at all (only the `notifications` build declares the listener). */
|
||||
val notificationsBuild: Boolean = false,
|
||||
/** The navigation apps installed: NavApp ids. */
|
||||
val navApps: List<String> = emptyList(),
|
||||
/** The instance's models, for Settings › Assistant › Assistant model; empty until (or unless) it said them. */
|
||||
val assistantModels: List<ModelInfo> = emptyList(),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit, onMcp: () -> Unit = {}) {
|
||||
val context = LocalContext.current
|
||||
val store = context.lembas.instances
|
||||
val scope = rememberCoroutineScope()
|
||||
val instances by store.instances.collectAsState(initial = emptyList())
|
||||
val active by store.active.collectAsState(initial = null)
|
||||
val prefs by store.prefs.collectAsState(initial = Prefs())
|
||||
val wakeState by WakeStatus.state.collectAsState()
|
||||
val assistantConnected by AssistLink.connected.collectAsState()
|
||||
// The test's ten seconds: its deadline is WakeStatus's, the clock that watches it is here.
|
||||
val trial by WakeStatus.trial.collectAsState()
|
||||
var clock by remember { mutableStateOf(SystemClock.elapsedRealtime()) }
|
||||
var tested by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(trial.until) {
|
||||
while (SystemClock.elapsedRealtime() < trial.until) {
|
||||
clock = SystemClock.elapsedRealtime()
|
||||
delay(200)
|
||||
}
|
||||
clock = SystemClock.elapsedRealtime()
|
||||
}
|
||||
// The instance's models, for the assistant's: asked for each time Settings opens on an instance.
|
||||
var models by remember { mutableStateOf(emptyList<ModelInfo>()) }
|
||||
LaunchedEffect(active?.id) {
|
||||
models = try {
|
||||
store.client()?.models().orEmpty()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// Not reachable now: the row keeps what was chosen and offers the instance's default.
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
var pushNote by remember { mutableStateOf<String?>(null) }
|
||||
var updateNote by remember { mutableStateOf<String?>(null) }
|
||||
var updateFound by remember { mutableStateOf<UpdateOffer?>(null) }
|
||||
val beta = remember { AppVersion.parse(BuildConfig.VERSION_NAME)?.isBeta ?: false }
|
||||
val distributors = remember { Push.distributors(context) }
|
||||
// The wake word needs the microphone before it can be turned on.
|
||||
val micForWake = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) {
|
||||
scope.launch {
|
||||
store.savePrefs { it.copy(wakeWord = true) }
|
||||
WakeWordService.start(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
val actions = remember {
|
||||
object : SettingsActions {
|
||||
override fun use(instance: Instance) {
|
||||
scope.launch { store.use(instance.id) }
|
||||
scope.launch {
|
||||
store.use(instance.id)
|
||||
// Copies of one instance's files are not kept around while another is in use.
|
||||
FileCache.clear(context)
|
||||
}
|
||||
}
|
||||
|
||||
override fun add() = onAddInstance()
|
||||
|
||||
override fun mcpServers() = onMcp()
|
||||
|
||||
override fun signOut(instance: Instance) {
|
||||
scope.launch {
|
||||
Push.disable(context, instance)
|
||||
runCatching { store.clientFor(instance).signOut() }
|
||||
store.remove(instance.id)
|
||||
// The copies of the account's files this phone held for a viewer or another app go with it.
|
||||
FileCache.clear(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,6 +312,10 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
scope.launch { store.savePrefs { it.copy(assistantTemporary = on) } }
|
||||
}
|
||||
|
||||
override fun assistantModel(id: String) {
|
||||
scope.launch { store.savePrefs { it.copy(assistantModel = id) } }
|
||||
}
|
||||
|
||||
override fun voiceInput(value: String) {
|
||||
scope.launch { store.savePrefs { it.copy(voiceInput = value) } }
|
||||
}
|
||||
@@ -196,6 +324,74 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
scope.launch { store.savePrefs { it.copy(assistantListens = on) } }
|
||||
}
|
||||
|
||||
override fun assistantConversation(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(assistantConversation = on) } }
|
||||
}
|
||||
|
||||
override fun wakeWord(on: Boolean) {
|
||||
val mic = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
when {
|
||||
on && !mic -> micForWake.launch(Manifest.permission.RECORD_AUDIO)
|
||||
|
||||
on -> scope.launch {
|
||||
store.savePrefs { it.copy(wakeWord = true) }
|
||||
WakeWordService.start(context)
|
||||
}
|
||||
|
||||
else -> scope.launch {
|
||||
store.savePrefs { it.copy(wakeWord = false) }
|
||||
WakeWordService.stop()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun wakePhrase(id: String) {
|
||||
scope.launch { store.savePrefs { it.copy(wakePhrase = id) } }
|
||||
}
|
||||
|
||||
override fun wakeSensitivity(id: String) {
|
||||
scope.launch { store.savePrefs { it.copy(wakeSensitivity = id) } }
|
||||
}
|
||||
|
||||
// A tap on the wake word's state: start it if the phone stopped it (asking for the
|
||||
// microphone where that is missing), and if it is waiting to try again, try now.
|
||||
override fun wakeRetry() {
|
||||
WakeStatus.retryNow()
|
||||
wakeWord(true)
|
||||
}
|
||||
|
||||
override fun wakeTest() {
|
||||
tested = true
|
||||
WakeStatus.startTrial(SystemClock.elapsedRealtime())
|
||||
}
|
||||
|
||||
override fun wakeScreenOnly(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(wakeScreenOnly = on) } }
|
||||
}
|
||||
|
||||
// The list of apps the phone's battery optimisation leaves alone; no permission needed to open it.
|
||||
override fun batterySettings() {
|
||||
runCatching { context.startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
||||
}
|
||||
|
||||
// On: Android's own switch is the person's to flip, so its page opens if it is off.
|
||||
override fun notificationSummaries(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(notificationSummaries = on) } }
|
||||
if (on && !NotificationAccess.granted(context)) notificationAccess()
|
||||
}
|
||||
|
||||
override fun notificationAccess() {
|
||||
NotificationAccess.settingsIntent(context)?.let { page -> runCatching { context.startActivity(page) } }
|
||||
}
|
||||
|
||||
override fun navApp(id: String) {
|
||||
scope.launch { store.savePrefs { it.copy(navApp = id) } }
|
||||
}
|
||||
|
||||
override fun osmandInfo(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(osmandInfo = on) } }
|
||||
}
|
||||
|
||||
override fun readAloud(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } }
|
||||
}
|
||||
@@ -250,6 +446,18 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
selfUpdate = BuildConfig.SELF_UPDATE,
|
||||
beta = beta,
|
||||
phoneRecognizer = remember { PhoneRecognizer.available(context) },
|
||||
wakeAvailable = WakeEngine.AVAILABLE,
|
||||
wakeState = wakeState,
|
||||
// Read again each time Settings is composed: the person comes back from the system's page.
|
||||
isAssistant = LembasAssistService.holdsRole(context),
|
||||
assistantConnected = assistantConnected,
|
||||
assistantActive = LembasAssistService.isActive(context),
|
||||
wakeTest = WakeTestShown(running = clock < trial.until, done = tested && clock >= trial.until, heard = if (tested) trial.heard else 0),
|
||||
// Read again each time Settings is composed: the person comes back from the system's page.
|
||||
notificationAccess = NotificationAccess.granted(context),
|
||||
notificationsBuild = NotificationAccess.AVAILABLE,
|
||||
navApps = remember { NavApp.installedApps(context).map { it.id } },
|
||||
assistantModels = models,
|
||||
),
|
||||
actions,
|
||||
onBack,
|
||||
@@ -265,6 +473,24 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
var choosingLanguage by remember { mutableStateOf(false) }
|
||||
var choosingWake by remember { mutableStateOf<WakeChoice?>(null) }
|
||||
choosingWake?.let { which ->
|
||||
ModalBottomSheet(onDismissRequest = { choosingWake = null }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
|
||||
WakeChoices(which, state.prefs, onPick = { pick ->
|
||||
choosingWake = null
|
||||
pick(actions)
|
||||
})
|
||||
}
|
||||
}
|
||||
var choosingModel by remember { mutableStateOf(false) }
|
||||
if (choosingModel) {
|
||||
ModalBottomSheet(onDismissRequest = { choosingModel = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
|
||||
AssistantModelChoices(state, onPick = {
|
||||
choosingModel = false
|
||||
actions.assistantModel(it)
|
||||
})
|
||||
}
|
||||
}
|
||||
if (choosingLanguage) {
|
||||
ModalBottomSheet(onDismissRequest = { choosingLanguage = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
|
||||
LanguageChoices(state.prefs, onPick = {
|
||||
@@ -330,6 +556,9 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
if (state.instances.isNotEmpty()) Rule()
|
||||
SettingRow(Icons.Filled.Add, stringResource(R.string.add_instance), onClick = actions::add)
|
||||
state.active?.let { current ->
|
||||
Rule()
|
||||
// The MCP servers of the instance in use, and which of them wait for a sign-in.
|
||||
SettingRow(Icons.Filled.Extension, stringResource(R.string.mcp_title), onClick = actions::mcpServers)
|
||||
Rule()
|
||||
SettingRow(Icons.AutoMirrored.Filled.Logout, stringResource(R.string.sign_out), tint = palette.danger, onClick = {
|
||||
actions.signOut(current)
|
||||
@@ -388,6 +617,15 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
onClick = actions::assistantSettings,
|
||||
)
|
||||
Rule()
|
||||
// The model the assistant's new chats start on: the instance's default may be
|
||||
// a large one, and a spoken question wants a quick answer.
|
||||
SettingRow(
|
||||
Icons.Filled.Psychology,
|
||||
stringResource(R.string.assistant_model),
|
||||
subtitle = assistantModelLabel(state),
|
||||
onClick = { choosingModel = true },
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Timer,
|
||||
stringResource(R.string.assistant_temporary),
|
||||
@@ -398,6 +636,7 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
SettingRow(
|
||||
Icons.Filled.Mic,
|
||||
stringResource(R.string.assistant_listens),
|
||||
badge = stringResource(R.string.experimental),
|
||||
onClick = { actions.assistantListens(!state.prefs.assistantListens) },
|
||||
trailing = { Switch(checked = state.prefs.assistantListens, onCheckedChange = actions::assistantListens) },
|
||||
)
|
||||
@@ -408,14 +647,40 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
onClick = { actions.readAloud(!state.prefs.readAloudSpoken) },
|
||||
trailing = { Switch(checked = state.prefs.readAloudSpoken, onCheckedChange = actions::readAloud) },
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Forum,
|
||||
stringResource(R.string.assistant_conversation),
|
||||
subtitle = stringResource(R.string.assistant_conversation_line),
|
||||
badge = stringResource(R.string.experimental),
|
||||
enabled = state.prefs.readAloudSpoken,
|
||||
onClick = { actions.assistantConversation(!state.prefs.assistantConversation) },
|
||||
trailing = {
|
||||
Switch(
|
||||
checked = state.prefs.assistantConversation && state.prefs.readAloudSpoken,
|
||||
enabled = state.prefs.readAloudSpoken,
|
||||
onCheckedChange = actions::assistantConversation,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
// Said plainly: which parts of the voice assistant are not to be relied on yet.
|
||||
Text(
|
||||
stringResource(R.string.assistant_samsung) + "\n\n" + stringResource(R.string.assist_no_wake_word),
|
||||
stringResource(R.string.assistant_voice_experimental_line),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 8.dp),
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.assistant_samsung),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
item { WakeWordGroup(state, actions, onChoose = { choosingWake = it }) }
|
||||
item { NotificationSummaryGroup(state, actions) }
|
||||
item { PhoneActionsGroup(state, actions) }
|
||||
item {
|
||||
// Which recogniser turns speech into words: the instance's or the phone's -- what
|
||||
// each one is, and where the recording goes, said in the row itself.
|
||||
@@ -497,21 +762,272 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
}
|
||||
}
|
||||
|
||||
/** The three things about the wake word that are chosen from a list, each in a sheet. */
|
||||
enum class WakeChoice { Greeting, Name, Sensitivity }
|
||||
|
||||
/**
|
||||
* The wake word: off until turned on; the phrase as a greeting and a name (English, words the
|
||||
* engine's model knows); how easily it is taken as heard; only while the screen is on; and what
|
||||
* it costs and why a phone may stop it, said before it is turned on.
|
||||
*/
|
||||
@Composable
|
||||
private fun Group(title: String, content: @Composable () -> Unit) {
|
||||
internal fun WakeWordGroup(state: SettingsState, actions: SettingsActions, onChoose: (WakeChoice) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val on = state.prefs.wakeWord && state.wakeAvailable
|
||||
Group(stringResource(R.string.wake_word), badge = stringResource(R.string.experimental)) {
|
||||
SettingRow(
|
||||
Icons.Filled.Hearing,
|
||||
stringResource(R.string.wake_word_listen),
|
||||
subtitle = if (state.wakeAvailable) {
|
||||
stringResource(R.string.wake_word_line) + "\n" + stringResource(R.string.wake_experimental_line)
|
||||
} else {
|
||||
stringResource(R.string.wake_word_unavailable)
|
||||
},
|
||||
enabled = state.wakeAvailable,
|
||||
onClick = { actions.wakeWord(!on) },
|
||||
trailing = { Switch(checked = on, enabled = state.wakeAvailable, onCheckedChange = actions::wakeWord) },
|
||||
)
|
||||
if (on) {
|
||||
// The truth, not the setting: listening, paused and why, or failed and why. A tap
|
||||
// tries again (and asks for the microphone when that is what is missing).
|
||||
val wake = state.wakeState
|
||||
val trouble = wake is WakeState.Failed || wake == WakeState.Off || wake == WakeState.Paused(WakePause.NoMicrophone)
|
||||
Rule()
|
||||
SettingRow(
|
||||
if (trouble) Icons.Filled.ErrorOutline else Icons.Filled.GraphicEq,
|
||||
wakeTitle(LocalContext.current, wake),
|
||||
subtitle = when {
|
||||
wake is WakeState.Failed && wake.why != WakeFailure.NoEngine ->
|
||||
listOf(stringResource(R.string.wake_failed_line), wake.detail).filter { it.isNotBlank() }.joinToString("\n")
|
||||
|
||||
wake == WakeState.Off || wake == WakeState.Paused(WakePause.NoMicrophone) -> stringResource(R.string.wake_tap_to_start)
|
||||
|
||||
else -> null
|
||||
},
|
||||
tint = if (trouble) palette.warning else null,
|
||||
onClick = actions::wakeRetry,
|
||||
)
|
||||
if (!state.isAssistant) {
|
||||
// Said plainly: Android lets only the phone's assistant open over other apps.
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Assistant,
|
||||
stringResource(R.string.wake_not_assistant),
|
||||
subtitle = stringResource(R.string.wake_not_assistant_line),
|
||||
onClick = actions::assistantSettings,
|
||||
)
|
||||
} else if (!state.assistantActive) {
|
||||
// Chosen as the assistant, yet Android does not run it as its voice assistant:
|
||||
// the long press opens it as an ordinary screen, and nothing is connected that
|
||||
// could open it from the background. Choosing it again puts that right.
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Assistant,
|
||||
stringResource(R.string.wake_assistant_inactive),
|
||||
subtitle = stringResource(R.string.wake_assistant_inactive_line),
|
||||
tint = palette.warning,
|
||||
onClick = actions::assistantSettings,
|
||||
)
|
||||
} else if (!state.assistantConnected) {
|
||||
// The assistant in name, but Android holds no connection to it at this moment:
|
||||
// the one thing that lets the sheet open from the background is missing.
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Assistant,
|
||||
stringResource(R.string.wake_assistant_unbound),
|
||||
subtitle = stringResource(R.string.wake_assistant_unbound_line),
|
||||
tint = palette.warning,
|
||||
onClick = actions::assistantSettings,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (state.wakeAvailable) {
|
||||
val phrase = WakePhrases.byId(state.prefs.wakePhrase)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.RecordVoiceOver,
|
||||
"“${phrase.words}”",
|
||||
subtitle = stringResource(R.string.wake_phrase_line),
|
||||
onClick = { onChoose(WakeChoice.Name) },
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.RecordVoiceOver,
|
||||
stringResource(R.string.wake_greeting),
|
||||
subtitle = phrase.greeting.words,
|
||||
showIcon = false,
|
||||
onClick = { onChoose(WakeChoice.Greeting) },
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.RecordVoiceOver,
|
||||
stringResource(R.string.wake_name),
|
||||
subtitle = if (phrase.name.id == GOOGLE) phrase.name.words + " · " + stringResource(R.string.wake_name_google_line) else phrase.name.words,
|
||||
showIcon = false,
|
||||
onClick = { onChoose(WakeChoice.Name) },
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Tune,
|
||||
stringResource(R.string.wake_sensitivity),
|
||||
subtitle = stringResource(sensitivityLabel(WakeSensitivity.byId(state.prefs.wakeSensitivity))),
|
||||
onClick = { onChoose(WakeChoice.Sensitivity) },
|
||||
)
|
||||
Rule()
|
||||
WakeTestRow(state, on, phrase.words, actions)
|
||||
Rule()
|
||||
WakeLogRow(state.prefs.wakeLog)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.ScreenLockPortrait,
|
||||
stringResource(R.string.wake_screen_only),
|
||||
subtitle = stringResource(R.string.wake_screen_only_line),
|
||||
onClick = { actions.wakeScreenOnly(!state.prefs.wakeScreenOnly) },
|
||||
trailing = { Switch(checked = state.prefs.wakeScreenOnly, onCheckedChange = actions::wakeScreenOnly) },
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.BatteryAlert,
|
||||
stringResource(R.string.wake_battery),
|
||||
subtitle = stringResource(R.string.wake_battery_line),
|
||||
onClick = actions::batterySettings,
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = palette.accent,
|
||||
modifier = Modifier.padding(start = 16.dp, top = 24.dp, bottom = 8.dp),
|
||||
stringResource(R.string.wake_word_privacy) + "\n\n" + stringResource(R.string.wake_word_cost),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Phone actions: which navigation app a route goes to (whichever is installed by default; with
|
||||
* both, the card asks), and whether OsmAnd may be asked where the phone is and where the running
|
||||
* route goes -- which the person allows inside OsmAnd first.
|
||||
*/
|
||||
@Composable
|
||||
private fun PhoneActionsGroup(state: SettingsState, actions: SettingsActions) {
|
||||
val palette = LocalPalette.current
|
||||
val choices = listOf(
|
||||
"" to stringResource(R.string.nav_app_auto),
|
||||
NavApp.GoogleMaps.id to stringResource(R.string.nav_app_google),
|
||||
NavApp.OsmAnd.id to stringResource(R.string.nav_app_osmand),
|
||||
NavApp.PREF_ASK to stringResource(R.string.nav_app_ask),
|
||||
)
|
||||
Group(stringResource(R.string.nav_app)) {
|
||||
choices.forEachIndexed { i, (id, label) ->
|
||||
if (i > 0) Rule()
|
||||
val installed = id == "" || id == NavApp.PREF_ASK || id in state.navApps
|
||||
SettingRow(
|
||||
Icons.Filled.Navigation,
|
||||
label,
|
||||
subtitle = if (installed) null else stringResource(R.string.nav_app_not_installed),
|
||||
showIcon = i == 0,
|
||||
enabled = installed,
|
||||
onClick = { actions.navApp(id) },
|
||||
trailing = { RadioButton(selected = state.prefs.navApp == id, enabled = installed, onClick = { actions.navApp(id) }) },
|
||||
)
|
||||
}
|
||||
if (NavApp.OsmAnd.id in state.navApps) {
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.MyLocation,
|
||||
stringResource(R.string.osmand_info),
|
||||
subtitle = stringResource(R.string.osmand_info_line),
|
||||
onClick = { actions.osmandInfo(!state.prefs.osmandInfo) },
|
||||
trailing = { Switch(checked = state.prefs.osmandInfo, onCheckedChange = actions::osmandInfo) },
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.phone_actions_line),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Notification summaries: off by default; on needs Android's notification access too, which this
|
||||
* explains. In a build without the listener the group says which build has it, and why.
|
||||
*/
|
||||
@Composable
|
||||
internal fun NotificationSummaryGroup(state: SettingsState, actions: SettingsActions) {
|
||||
val palette = LocalPalette.current
|
||||
val on = state.prefs.notificationSummaries
|
||||
Group(stringResource(R.string.notification_summaries)) {
|
||||
if (!state.notificationsBuild) {
|
||||
SettingRow(
|
||||
Icons.Filled.Notifications,
|
||||
stringResource(R.string.notification_summaries_switch),
|
||||
subtitle = stringResource(R.string.notification_summaries_unavailable),
|
||||
enabled = false,
|
||||
onClick = {},
|
||||
)
|
||||
} else {
|
||||
SettingRow(
|
||||
Icons.Filled.Notifications,
|
||||
stringResource(R.string.notification_summaries_switch),
|
||||
subtitle = stringResource(R.string.notification_summaries_line),
|
||||
onClick = { actions.notificationSummaries(!on) },
|
||||
trailing = { Switch(checked = on, onCheckedChange = actions::notificationSummaries) },
|
||||
)
|
||||
if (on) {
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Security,
|
||||
stringResource(R.string.notification_access),
|
||||
subtitle = stringResource(if (state.notificationAccess) R.string.notification_access_on else R.string.notification_access_off),
|
||||
tint = if (state.notificationAccess) null else palette.warning,
|
||||
onClick = actions::notificationAccess,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.notificationsBuild) {
|
||||
Text(
|
||||
stringResource(R.string.notification_summaries_privacy),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** A group's header and its rows; [badge] is a label beside the title ("Experimental"). */
|
||||
@Composable
|
||||
private fun Group(title: String, badge: String? = null, content: @Composable () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
// The title gives when the two do not fit; the label keeps its size.
|
||||
Row(Modifier.padding(start = 16.dp, end = 16.dp, top = 24.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = palette.accent,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
if (badge != null) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Badge(badge)
|
||||
}
|
||||
}
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column { content() }
|
||||
}
|
||||
}
|
||||
|
||||
/** A small label: "Experimental". */
|
||||
@Composable
|
||||
private fun Badge(text: String) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(shape = RoundedCornerShape(8.dp), color = palette.accentSoft, contentColor = palette.accent) {
|
||||
Text(text, style = MaterialTheme.typography.labelSmall, maxLines = 1, modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Rule() = HorizontalDivider(color = LocalPalette.current.border, modifier = Modifier.padding(start = 56.dp))
|
||||
|
||||
@@ -528,6 +1044,7 @@ private fun SettingRow(
|
||||
tint: Color? = null,
|
||||
enabled: Boolean = true,
|
||||
showIcon: Boolean = true,
|
||||
badge: String? = null,
|
||||
trailing: (@Composable () -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
@@ -546,6 +1063,8 @@ private fun SettingRow(
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge, color = ink)
|
||||
// On a line of its own, under the title: nothing has to fit beside words that wrap.
|
||||
badge?.let { Box(Modifier.padding(top = 2.dp, bottom = 2.dp)) { Badge(it) } }
|
||||
subtitle?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) }
|
||||
}
|
||||
if (trailing != null) {
|
||||
@@ -581,6 +1100,174 @@ private fun languageLabel(prefs: Prefs): String = when (prefs.language) {
|
||||
else -> AppLanguage.name(prefs.language) ?: stringResource(R.string.language_account)
|
||||
}
|
||||
|
||||
/**
|
||||
* "Test the wake word": for ten seconds the row says what the wake word is doing and whether the
|
||||
* phrase landed ("Heard it"), while the assistant stays shut -- so the phrase, the sensitivity and
|
||||
* the place can be tried without a sheet opening each time.
|
||||
*/
|
||||
@Composable
|
||||
private fun WakeTestRow(state: SettingsState, on: Boolean, phrase: String, actions: SettingsActions) {
|
||||
val palette = LocalPalette.current
|
||||
val test = state.wakeTest
|
||||
val heard = stringResource(R.string.wake_test_heard) + if (test.heard > 1) " ×${test.heard}" else ""
|
||||
val say = stringResource(R.string.wake_test_say, phrase)
|
||||
SettingRow(
|
||||
if (test.heard > 0) Icons.Filled.CheckCircle else Icons.Filled.Mic,
|
||||
stringResource(R.string.wake_test),
|
||||
subtitle = when {
|
||||
!on -> stringResource(R.string.wake_test_off)
|
||||
test.running && test.heard > 0 -> heard + "\n" + say
|
||||
test.running -> say + "\n" + wakeTitle(LocalContext.current, state.wakeState)
|
||||
test.done && test.heard > 0 -> heard
|
||||
test.done -> stringResource(R.string.wake_test_missed)
|
||||
else -> stringResource(R.string.wake_test_line)
|
||||
},
|
||||
tint = when {
|
||||
!on -> null
|
||||
test.heard > 0 -> palette.accent
|
||||
test.done -> palette.warning
|
||||
else -> null
|
||||
},
|
||||
enabled = on,
|
||||
onClick = actions::wakeTest,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* "Last wake": what happened the last time the phrase was heard -- what was tried and how it
|
||||
* went, in plain words, with Android's own where it refused -- and, on a tap, the few before it.
|
||||
*/
|
||||
@Composable
|
||||
private fun WakeLogRow(log: List<WakeAttempt>) {
|
||||
val context = LocalContext.current
|
||||
var all by remember { mutableStateOf(false) }
|
||||
val shown = if (all) log else log.take(1)
|
||||
SettingRow(
|
||||
Icons.Filled.History,
|
||||
stringResource(R.string.wake_last),
|
||||
subtitle = if (log.isEmpty()) {
|
||||
stringResource(R.string.wake_last_none)
|
||||
} else {
|
||||
shown.joinToString("\n\n") { wakeAttemptWords(context, it).joinToString("\n") }
|
||||
},
|
||||
enabled = log.isNotEmpty(),
|
||||
onClick = { all = !all },
|
||||
)
|
||||
}
|
||||
|
||||
private const val GOOGLE = "google"
|
||||
|
||||
private fun sensitivityLabel(sensitivity: WakeSensitivity): Int = when (sensitivity) {
|
||||
WakeSensitivity.Low -> R.string.wake_sensitivity_low
|
||||
WakeSensitivity.Normal -> R.string.wake_sensitivity_normal
|
||||
WakeSensitivity.High -> R.string.wake_sensitivity_high
|
||||
}
|
||||
|
||||
/**
|
||||
* One of the wake word's lists, as a sheet: the greetings, the names (Google's says that a Google
|
||||
* device nearby answers to it too), or the sensitivity with what each step trades. A pick is
|
||||
* handed back as what to do with the actions.
|
||||
*/
|
||||
@Composable
|
||||
fun WakeChoices(which: WakeChoice, prefs: Prefs, onPick: ((SettingsActions) -> Unit) -> Unit) {
|
||||
val phrase = WakePhrases.byId(prefs.wakePhrase)
|
||||
val google = stringResource(R.string.wake_name_google_line)
|
||||
val title = stringResource(
|
||||
when (which) {
|
||||
WakeChoice.Greeting -> R.string.wake_greeting
|
||||
WakeChoice.Name -> R.string.wake_name
|
||||
WakeChoice.Sensitivity -> R.string.wake_sensitivity
|
||||
},
|
||||
)
|
||||
// id, words, a line under them, whether it is the one chosen.
|
||||
val choices: List<Choice> = when (which) {
|
||||
WakeChoice.Greeting -> WakeWords.greetings.map { Choice(WakePhrase(it, phrase.name).id, it.words, null, it.id == phrase.greeting.id) }
|
||||
|
||||
WakeChoice.Name -> WakeWords.names.map {
|
||||
Choice(WakePhrase(phrase.greeting, it).id, it.words, if (it.id == GOOGLE) google else null, it.id == phrase.name.id)
|
||||
}
|
||||
|
||||
WakeChoice.Sensitivity -> WakeSensitivity.entries.map {
|
||||
val line = when (it) {
|
||||
WakeSensitivity.Low -> R.string.wake_sensitivity_low_line
|
||||
WakeSensitivity.Normal -> R.string.wake_sensitivity_normal_line
|
||||
WakeSensitivity.High -> R.string.wake_sensitivity_high_line
|
||||
}
|
||||
Choice(it.id, stringResource(sensitivityLabel(it)), stringResource(line), it.id == WakeSensitivity.byId(prefs.wakeSensitivity).id)
|
||||
}
|
||||
}
|
||||
ChoiceList(title, choices) { id ->
|
||||
onPick { actions -> if (which == WakeChoice.Sensitivity) actions.wakeSensitivity(id) else actions.wakePhrase(id) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the assistant's model row says: the chosen model by its name, or "Instance default" --
|
||||
* also for a model the instance no longer has, since that is what the assistant then uses.
|
||||
*/
|
||||
@Composable
|
||||
private fun assistantModelLabel(state: SettingsState): String {
|
||||
val chosen = state.prefs.assistantModel
|
||||
val model = state.assistantModels.named(chosen)
|
||||
// While the list is not read yet, or could not be: the choice as it was saved.
|
||||
return when {
|
||||
chosen.isBlank() -> stringResource(R.string.assistant_model_default)
|
||||
model != null -> model.titleAmong(state.assistantModels)
|
||||
state.assistantModels.isEmpty() -> chosen
|
||||
else -> stringResource(R.string.assistant_model_default)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings › Assistant › Assistant model, as a sheet: "Instance default" (the account's default
|
||||
* model, as in a new chat in the app), then the instance's models. The choice is the model a new
|
||||
* assistant chat starts on, from every way in -- the sheet, the wake word, Share.
|
||||
*/
|
||||
@Composable
|
||||
fun AssistantModelChoices(state: SettingsState, onPick: (String) -> Unit) {
|
||||
// A choice saved before models had refs is an id: it still finds its model.
|
||||
val chosen = state.assistantModels.named(state.prefs.assistantModel)?.key.orEmpty()
|
||||
val choices = listOf(
|
||||
Choice(INSTANCE_DEFAULT, stringResource(R.string.assistant_model_default), stringResource(R.string.assistant_model_default_line), chosen.isEmpty()),
|
||||
) + state.assistantModels.distinctBy { it.key }.map { Choice(it.key, it.titleAmong(state.assistantModels), null, it.key == chosen) }
|
||||
ChoiceList(stringResource(R.string.assistant_model), choices) { id -> onPick(if (id == INSTANCE_DEFAULT) "" else id) }
|
||||
}
|
||||
|
||||
/** The list's key for "Instance default": a key cannot be empty, and no model is named so. */
|
||||
private const val INSTANCE_DEFAULT = " default"
|
||||
|
||||
private data class Choice(val id: String, val title: String, val subtitle: String?, val chosen: Boolean)
|
||||
|
||||
/** A sheet's list of choices: a title, then rows of words that give and a radio button that keeps its size. */
|
||||
@Composable
|
||||
private fun ChoiceList(title: String, choices: List<Choice>, onPick: (String) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
LazyColumn(Modifier.fillMaxWidth(), contentPadding = PaddingValues(bottom = 24.dp)) {
|
||||
item {
|
||||
Text(title, style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(start = 24.dp, end = 24.dp, bottom = 8.dp))
|
||||
}
|
||||
choices.forEach { choice ->
|
||||
item(key = choice.id) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onPick(choice.id) }
|
||||
.heightIn(min = 56.dp)
|
||||
.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(choice.title, style = MaterialTheme.typography.bodyLarge)
|
||||
choice.subtitle?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) }
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
RadioButton(selected = choice.chosen, onClick = { onPick(choice.id) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings › Language, as a sheet: the account's language (the default), the phone's, then every
|
||||
* language the app has, each named in itself so a person who cannot read the current one still
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.9. Do not edit.
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.19. Do not edit.
|
||||
package eu.llembas.android.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
package eu.llembas.android.ui.viewer
|
||||
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.gestures.detectTransformGestures
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.Pause
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material3.FilledIconButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Slider
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clipToBounds
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ArchiveListing
|
||||
import eu.llembas.android.api.Notebook
|
||||
import eu.llembas.android.api.Table
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import java.util.Locale
|
||||
|
||||
// What the viewer draws for each kind of file, each from its state alone (the screenshot tests
|
||||
// draw these). Everything a file holds is drawn as text or as pixels the app decoded itself:
|
||||
// nothing here interprets a file -- no HTML, no script, no WebView.
|
||||
|
||||
/** What the details page can do; nothing by default, for the screenshot tests. */
|
||||
interface FileActions {
|
||||
fun download() {}
|
||||
|
||||
fun openWith() {}
|
||||
|
||||
fun share() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* A file there is nothing to draw of (an archive, a 3D model, a binary, or one a viewer could
|
||||
* not show): what it is, [note] saying why it is not shown, and the three ways out. The
|
||||
* buttons stack: their words are of unknown length in nine languages.
|
||||
*/
|
||||
@Composable
|
||||
fun DetailsBody(name: String, type: String, size: Long, note: String?, actions: FileActions) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Column(
|
||||
Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Icon(Icons.AutoMirrored.Filled.InsertDriveFile, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.size(56.dp))
|
||||
Text(name, style = MaterialTheme.typography.titleMedium, textAlign = TextAlign.Center)
|
||||
Column(Modifier.fillMaxWidth().border(1.dp, palette.border, RoundedCornerShape(16.dp)).padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
Fact(stringResource(R.string.files_type), type)
|
||||
Fact(stringResource(R.string.files_size), Formatter.formatShortFileSize(context, size))
|
||||
}
|
||||
note?.takeIf { it.isNotBlank() }?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, textAlign = TextAlign.Center) }
|
||||
OutlinedButton(onClick = actions::download, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text(stringResource(R.string.download)) }
|
||||
OutlinedButton(onClick = actions::openWith, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text(stringResource(R.string.files_open_with)) }
|
||||
OutlinedButton(onClick = actions::share, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text(stringResource(R.string.report_share)) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What an archive holds, as the instance lists it: every name is the archive's own text and is
|
||||
* drawn as text; nothing is unpacked, here or there. How many, the names with their sizes (a
|
||||
* name wraps, its size keeps its width), a line when there are more than are listed, and the
|
||||
* three ways out.
|
||||
*/
|
||||
@Composable
|
||||
fun ArchiveBody(archive: ArchiveListing, actions: FileActions) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(R.string.archive_entries, (archive.total ?: archive.entries.size).toString()),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
itemsIndexed(archive.entries) { _, entry ->
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 40.dp).padding(vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
if (entry.dir) Icons.Filled.Folder else Icons.AutoMirrored.Filled.InsertDriveFile,
|
||||
contentDescription = null,
|
||||
tint = palette.inkFaint,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(entry.name, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
entry.size?.takeIf { !entry.dir }?.let {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(Formatter.formatShortFileSize(context, it), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (archive.truncated) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(R.string.archive_cut, archive.entries.size.toString()),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
item {
|
||||
Column(Modifier.fillMaxWidth().padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedButton(onClick = actions::download, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.download))
|
||||
}
|
||||
OutlinedButton(onClick = actions::openWith, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.files_open_with))
|
||||
}
|
||||
OutlinedButton(onClick = actions::share, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.report_share))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A label and its value on one line: the label keeps its width, the value takes the rest and wraps. */
|
||||
@Composable
|
||||
private fun Fact(label: String, value: String) {
|
||||
val palette = LocalPalette.current
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
|
||||
Text(label, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, modifier = Modifier.width(96.dp))
|
||||
Text(value, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
|
||||
/** The width every column of a table has: fixed, so a row's cells line up whatever they hold. */
|
||||
private val COLUMN = 148.dp
|
||||
|
||||
/**
|
||||
* A CSV or TSV file as a grid: every cell one line in a column of one width, the first row as
|
||||
* the heading, the whole grid scrolling sideways as one and down as a list. Cells are text.
|
||||
*/
|
||||
@Composable
|
||||
fun TableBody(table: Table) {
|
||||
val palette = LocalPalette.current
|
||||
val sideways = rememberScrollState()
|
||||
val style = TextStyle(fontSize = 13.sp, lineHeight = 18.sp, color = palette.ink)
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
if (table.cut) Note(stringResource(R.string.table_cut))
|
||||
Box(Modifier.fillMaxSize().horizontalScroll(sideways)) {
|
||||
LazyColumn(Modifier.width(COLUMN * table.columns.coerceAtLeast(1))) {
|
||||
itemsIndexed(table.rows) { i, row ->
|
||||
Row(Modifier.background(if (i == 0) palette.bgSunken else palette.bg)) {
|
||||
for (c in 0 until table.columns.coerceAtLeast(1)) {
|
||||
Text(
|
||||
row.getOrElse(c) { "" },
|
||||
style = if (i == 0) style.copy(fontWeight = FontWeight.SemiBold) else style,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.width(COLUMN).border(0.5.dp, palette.border).padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A quiet line above a body, saying what is not shown. */
|
||||
@Composable
|
||||
internal fun Note(text: String) {
|
||||
val palette = LocalPalette.current
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.fillMaxWidth().background(palette.bgSunken).padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/** A notebook, read-only: each cell's source as text, and under it the plain text it printed. */
|
||||
@Composable
|
||||
fun NotebookBody(notebook: Notebook) {
|
||||
val palette = LocalPalette.current
|
||||
val mono = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp, lineHeight = 18.sp, color = palette.ink)
|
||||
if (notebook.cells.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.notebook_empty), color = palette.inkMuted, modifier = Modifier.padding(32.dp))
|
||||
}
|
||||
return
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
itemsIndexed(notebook.cells) { _, cell ->
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
if (cell.count != null) "${cell.kind} [${cell.count}]" else cell.kind,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(bottom = 4.dp),
|
||||
)
|
||||
val code = cell.kind == "code"
|
||||
Text(
|
||||
cell.source.ifEmpty { " " },
|
||||
style = if (code) mono else MaterialTheme.typography.bodyMedium.copy(color = palette.ink),
|
||||
// Code sits on the code's ground; a cell of prose is prose on the page.
|
||||
modifier = Modifier.fillMaxWidth().then(
|
||||
if (code) Modifier.background(palette.codeBg, RoundedCornerShape(8.dp)).padding(10.dp) else Modifier,
|
||||
),
|
||||
)
|
||||
if (cell.output.isNotEmpty()) {
|
||||
Text(cell.output, style = mono.copy(color = palette.inkMuted), modifier = Modifier.fillMaxWidth().padding(start = 10.dp, top = 6.dp))
|
||||
}
|
||||
if (cell.cut) Text(stringResource(R.string.notebook_cell_cut), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
}
|
||||
if (notebook.more > 0) {
|
||||
item {
|
||||
Text(stringResource(R.string.notebook_more, notebook.more.toString()), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How far a picture zoomed to [scale] may be moved inside a view of [size]: never past its own edge. */
|
||||
fun clampPan(offset: Offset, scale: Float, size: IntSize): Offset {
|
||||
val x = size.width * (scale - 1f) / 2f
|
||||
val y = size.height * (scale - 1f) / 2f
|
||||
return Offset(offset.x.coerceIn(-x, x), offset.y.coerceIn(-y, y))
|
||||
}
|
||||
|
||||
const val ZOOM_MAX = 8f
|
||||
|
||||
/** A picture, whole: two fingers zoom and move it, a double tap zooms in and back. */
|
||||
@Composable
|
||||
fun ZoomableImage(bitmap: ImageBitmap, description: String) {
|
||||
val palette = LocalPalette.current
|
||||
var scale by remember(bitmap) { mutableFloatStateOf(1f) }
|
||||
var offset by remember(bitmap) { mutableStateOf(Offset.Zero) }
|
||||
var size by remember { mutableStateOf(IntSize.Zero) }
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(palette.bgSunken)
|
||||
.clipToBounds()
|
||||
.onSizeChanged { size = it }
|
||||
.pointerInput(bitmap) {
|
||||
detectTransformGestures { _, pan, zoom, _ ->
|
||||
scale = (scale * zoom).coerceIn(1f, ZOOM_MAX)
|
||||
offset = clampPan(offset + pan, scale, size)
|
||||
}
|
||||
}
|
||||
.pointerInput(bitmap) {
|
||||
detectTapGestures(
|
||||
onDoubleTap = {
|
||||
scale = if (scale > 1f) 1f else 3f
|
||||
offset = Offset.Zero
|
||||
},
|
||||
)
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Image(
|
||||
bitmap,
|
||||
contentDescription = description,
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = Modifier.fillMaxSize().graphicsLayer {
|
||||
scaleX = scale
|
||||
scaleY = scale
|
||||
translationX = offset.x
|
||||
translationY = offset.y
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** What a player shows: whether it can play yet, is playing, where it is and how long the file is. */
|
||||
data class PlayerUi(val ready: Boolean = false, val playing: Boolean = false, val positionMs: Int = 0, val durationMs: Int = 0)
|
||||
|
||||
/** `m:ss`, or `h:mm:ss` from an hour on: a time read off a player, the same in every language. */
|
||||
fun playTime(ms: Int): String {
|
||||
val all = (ms.coerceAtLeast(0) / 1000)
|
||||
val h = all / 3600
|
||||
val m = all % 3600 / 60
|
||||
val s = all % 60
|
||||
return if (h > 0) String.format(Locale.ROOT, "%d:%02d:%02d", h, m, s) else String.format(Locale.ROOT, "%d:%02d", m, s)
|
||||
}
|
||||
|
||||
/**
|
||||
* A player's controls: the place in the file as a slider the whole width, the two times under
|
||||
* its two ends, and Play or Pause in the middle (56 dp). Nothing here depends on a text's length.
|
||||
*/
|
||||
@Composable
|
||||
fun PlayerControls(ui: PlayerUi, onToggle: () -> Unit, onSeek: (Int) -> Unit, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
var dragging by remember { mutableStateOf<Float?>(null) }
|
||||
val length = ui.durationMs.coerceAtLeast(1).toFloat()
|
||||
Column(modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Slider(
|
||||
value = (dragging ?: ui.positionMs.toFloat()).coerceIn(0f, length),
|
||||
onValueChange = { dragging = it },
|
||||
onValueChangeFinished = {
|
||||
dragging?.let { onSeek(it.toInt()) }
|
||||
dragging = null
|
||||
},
|
||||
valueRange = 0f..length,
|
||||
enabled = ui.ready && ui.durationMs > 0,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Text(playTime((dragging ?: ui.positionMs.toFloat()).toInt()), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(playTime(ui.durationMs), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
FilledIconButton(
|
||||
onClick = onToggle,
|
||||
enabled = ui.ready,
|
||||
colors = IconButtonDefaults.filledIconButtonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.size(56.dp),
|
||||
) {
|
||||
Icon(
|
||||
if (ui.playing) Icons.Filled.Pause else Icons.Filled.PlayArrow,
|
||||
contentDescription = stringResource(if (ui.playing) R.string.pause else R.string.play),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A text file being edited: the whole text in one field, in the code's type. The field is the
|
||||
* screen; saving and leaving are the bar's.
|
||||
*/
|
||||
@Composable
|
||||
fun EditorBody(text: String, onChange: (String) -> Unit, enabled: Boolean = true) {
|
||||
val palette = LocalPalette.current
|
||||
BasicTextField(
|
||||
value = text,
|
||||
onValueChange = onChange,
|
||||
enabled = enabled,
|
||||
textStyle = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 14.sp, lineHeight = 20.sp, color = palette.ink),
|
||||
cursorBrush = SolidColor(palette.accent),
|
||||
modifier = Modifier.fillMaxSize().background(palette.codeBg).padding(12.dp),
|
||||
)
|
||||
}
|
||||
@@ -38,13 +38,16 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
@@ -61,7 +64,11 @@ import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.highlight
|
||||
import eu.llembas.android.ui.highlights
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
@@ -74,15 +81,15 @@ private const val MARKDOWN_MAX_CHARS = 200_000
|
||||
private sealed interface Loaded {
|
||||
data object Loading : Loaded
|
||||
|
||||
/** [kind]: what the server said the file is, when it is only known once it came. */
|
||||
data class Text(val text: String, val kind: String? = null) : Loaded
|
||||
/** [kind], [language]: what the server said the file is, when it is only known once it came. */
|
||||
data class Text(val text: String, val kind: String? = null, val language: String? = null) : Loaded
|
||||
|
||||
/** [unavailable]: this server has no door for the app to read the file through. */
|
||||
data class Failed(val message: String, val unavailable: Boolean = false) : Loaded
|
||||
}
|
||||
|
||||
/** What the viewer's title and body need to know before the text comes. */
|
||||
private data class Viewed(val name: String, val path: String, val line: Int, val kind: String)
|
||||
private data class Viewed(val name: String, val path: String, val line: Int, val kind: String, val language: String = "")
|
||||
|
||||
/**
|
||||
* What a `show` card opens: the file, full screen, read-only, as the chat sees it now.
|
||||
@@ -97,7 +104,7 @@ private data class Viewed(val name: String, val path: String, val line: Int, val
|
||||
@Composable
|
||||
fun FileViewer(chatId: String, show: ShowCard, onClose: () -> Unit) {
|
||||
Viewer(
|
||||
file = Viewed(show.name, show.path, show.line, show.viewKind),
|
||||
file = Viewed(show.name, show.path, show.line, show.viewKind, show.language),
|
||||
key = chatId to show,
|
||||
webUrl = { it.webViewer(chatId, show) },
|
||||
load = { api, _ -> Loaded.Text(api.shownText(chatId, show)) },
|
||||
@@ -105,31 +112,6 @@ fun FileViewer(chatId: String, show: ShowCard, onClose: () -> Unit) {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A file of the person's tree (the Files screen), in the same viewer and under the same rules:
|
||||
* the person's own files are no more trusted than a model's, since a model may have written
|
||||
* them. A file the server withholds (not text, over 1 MB) says why, and offers the web UI.
|
||||
*/
|
||||
@Composable
|
||||
fun TreeFileViewer(path: String, onClose: () -> Unit) {
|
||||
Viewer(
|
||||
file = Viewed(path.substringAfterLast('/').ifBlank { path }, path, 0, "text"),
|
||||
key = path,
|
||||
webUrl = { it.webFile(path) },
|
||||
load = { api, context ->
|
||||
val file = api.fileContent(path)
|
||||
val withheld = file.withheld
|
||||
when {
|
||||
withheld == null -> Loaded.Text(file.text, file.viewKind)
|
||||
withheld.message.isNotBlank() -> Loaded.Failed(withheld.message)
|
||||
withheld.reason == "too_large" -> Loaded.Failed(context.getString(R.string.viewer_too_large))
|
||||
else -> Loaded.Failed(context.getString(R.string.viewer_not_text))
|
||||
}
|
||||
},
|
||||
onClose = onClose,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Viewer(file: Viewed, key: Any, webUrl: (ApiClient) -> String?, load: suspend (ApiClient, Context) -> Loaded, onClose: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
@@ -217,15 +199,20 @@ private fun Viewer(file: Viewed, key: Any, webUrl: (ApiClient) -> String?, load:
|
||||
}
|
||||
}
|
||||
|
||||
is Loaded.Text -> Body(now.kind ?: file.kind, file.line, now.text)
|
||||
is Loaded.Text -> FileBody(now.kind ?: file.kind, now.language ?: file.language, file.line, now.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A file's text as the viewer draws it, from these alone (what the screenshot tests draw):
|
||||
* Markdown rendered, anything else as numbered lines -- code in the theme's colours when its
|
||||
* [language] is one [highlight] reads. Read-only either way.
|
||||
*/
|
||||
@Composable
|
||||
private fun Body(kind: String, line: Int, text: String) {
|
||||
fun FileBody(kind: String, language: String, line: Int, text: String) {
|
||||
val palette = LocalPalette.current
|
||||
if (kind == "markdown" && text.length <= MARKDOWN_MAX_CHARS) {
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp)) {
|
||||
@@ -247,7 +234,7 @@ private fun Body(kind: String, line: Int, text: String) {
|
||||
modifier = Modifier.fillMaxWidth().background(palette.bgSunken).padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
Lines(text, line)
|
||||
Lines(text, line, language)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -258,12 +245,14 @@ private fun Body(kind: String, line: Int, text: String) {
|
||||
* text rather than under the numbers.
|
||||
*/
|
||||
@Composable
|
||||
private fun Lines(text: String, line: Int) {
|
||||
private fun Lines(text: String, line: Int, language: String) {
|
||||
val palette = LocalPalette.current
|
||||
val rows = remember(text) {
|
||||
val split = text.split('\n')
|
||||
if (split.size > 1 && split.last().isEmpty()) split.dropLast(1) else split
|
||||
val plain = remember(text) { linesOf(AnnotatedString(text)) }
|
||||
// Highlighted off the main thread: a long file shows plain for a moment, then in colour.
|
||||
val coloured by produceState<List<AnnotatedString>?>(null, text, language, palette) {
|
||||
if (highlights(language)) value = withContext(Dispatchers.Default) { linesOf(highlight(text, language, palette)) }
|
||||
}
|
||||
val rows = coloured ?: if (LocalInspectionMode.current && highlights(language)) linesOf(highlight(text, language, palette)) else plain
|
||||
val style = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp, lineHeight = 18.sp, color = palette.ink)
|
||||
val measurer = rememberTextMeasurer()
|
||||
val density = LocalDensity.current
|
||||
@@ -286,18 +275,33 @@ private fun Lines(text: String, line: Int) {
|
||||
) {
|
||||
Text((i + 1).toString(), style = style.copy(color = palette.inkFaint), textAlign = TextAlign.End, modifier = Modifier.width(gutter))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(row.ifEmpty { " " }, style = style, modifier = Modifier.weight(1f))
|
||||
Text(if (row.isEmpty()) AnnotatedString(" ") else row, style = style, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun copy(context: Context, label: String, text: String) {
|
||||
/** [text]'s lines, each with its own spans; a final newline makes no empty last line. */
|
||||
private fun linesOf(text: AnnotatedString): List<AnnotatedString> {
|
||||
val out = mutableListOf<AnnotatedString>()
|
||||
var start = 0
|
||||
while (true) {
|
||||
val end = text.text.indexOf('\n', start)
|
||||
if (end < 0) {
|
||||
if (start < text.length || out.isEmpty()) out += text.subSequence(start, text.length)
|
||||
return out
|
||||
}
|
||||
out += text.subSequence(start, end)
|
||||
start = end + 1
|
||||
}
|
||||
}
|
||||
|
||||
internal fun copy(context: Context, label: String, text: String) {
|
||||
context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText(label, text))
|
||||
}
|
||||
|
||||
/** The web UI's viewer, in the browser (a Custom Tab), where the person's own session is. */
|
||||
private fun openOutside(context: Context, url: String) {
|
||||
internal fun openOutside(context: Context, url: String) {
|
||||
val uri = Uri.parse(url)
|
||||
if (uri.scheme?.lowercase() !in setOf("http", "https")) return
|
||||
runCatching { CustomTabsIntent.Builder().build().launchUrl(context, uri) }
|
||||
|
||||
@@ -0,0 +1,582 @@
|
||||
package eu.llembas.android.ui.viewer
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.pdf.PdfRenderer
|
||||
import android.media.AudioAttributes
|
||||
import android.media.MediaDataSource
|
||||
import android.media.MediaPlayer
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LifecycleEventEffect
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.RangeReader
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.sampleFor
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.files.FileCache
|
||||
import eu.llembas.android.ui.files.copyInto
|
||||
import eu.llembas.android.ui.files.stepped
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.unreachable
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
|
||||
// The viewers that need the file's bytes: a picture, a PDF, sound and video. The bytes come
|
||||
// from the instance the app is signed in to, with the token in the Authorization header -- the
|
||||
// address handed to nothing: the platform's player reads through [RemoteMedia], which asks the
|
||||
// app's own HTTP client for each piece. No player library is added for this.
|
||||
|
||||
/** The most a picture's file may weigh to be decoded on the phone, and a PDF's to be copied for its pages. */
|
||||
const val IMAGE_MAX_BYTES = 64L * 1024 * 1024
|
||||
const val PDF_MAX_BYTES = 100L * 1024 * 1024
|
||||
|
||||
/** The most pages of a PDF that are laid out; a longer one is read to there and downloaded for the rest. */
|
||||
const val PDF_MAX_PAGES = 2000
|
||||
|
||||
/** How a viewer's bytes came: on their way ([done] of [total], -1 unknown), there, or not shown. */
|
||||
sealed interface Fetched<out T> {
|
||||
data class Loading(val done: Long = 0, val total: Long = -1) : Fetched<Nothing>
|
||||
|
||||
data class Ready<T>(val value: T) : Fetched<T>
|
||||
|
||||
/** [message]: the server's sentence or the network's; null: this phone could not draw it. */
|
||||
data class Failed(val message: String?) : Fetched<Nothing>
|
||||
}
|
||||
|
||||
/**
|
||||
* [file] decoded for the screen: its bounds are read first, and it is sampled down
|
||||
* ([sampleFor]) so neither edge nor the pixel count is more than a phone shows -- a picture
|
||||
* that claims a huge size costs a bounded amount of memory, or is not decoded at all.
|
||||
*/
|
||||
fun decodeCapped(file: File): Bitmap? {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(file.path, bounds)
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
|
||||
var sample = sampleFor(bounds.outWidth, bounds.outHeight)
|
||||
repeat(3) {
|
||||
try {
|
||||
return BitmapFactory.decodeFile(file.path, BitmapFactory.Options().apply { inSampleSize = sample })
|
||||
} catch (e: OutOfMemoryError) {
|
||||
sample *= 2
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** A picture of the tree: copied into the private cache (at most [IMAGE_MAX_BYTES]), decoded small, and the copy deleted at once. */
|
||||
@Composable
|
||||
fun ImageBody(path: String, name: String, size: Long, fallback: @Composable (String?) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val picture by produceState<Fetched<ImageBitmap>>(Fetched.Loading(), path) {
|
||||
if (size > IMAGE_MAX_BYTES) {
|
||||
value = Fetched.Failed(null)
|
||||
return@produceState
|
||||
}
|
||||
val copy = FileCache.viewing(context, name)
|
||||
value = try {
|
||||
val api = context.lembas.instances.client() ?: throw IOException(context.getString(R.string.assist_signed_out))
|
||||
context.lembas.gate.pass()
|
||||
api.copyInto(api.rawFile(path), copy, IMAGE_MAX_BYTES, stepped { done, total -> value = Fetched.Loading(done, total) })
|
||||
val bitmap = withContext(Dispatchers.Default) { decodeCapped(copy) }
|
||||
if (bitmap == null) Fetched.Failed(null) else Fetched.Ready(bitmap.asImageBitmap())
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Fetched.Failed(viewerSays(context, e))
|
||||
} finally {
|
||||
copy.delete()
|
||||
}
|
||||
}
|
||||
when (val now = picture) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> fallback(now.message)
|
||||
is Fetched.Ready -> ZoomableImage(now.value, name)
|
||||
}
|
||||
}
|
||||
|
||||
/** A transfer under way, in the middle of the page: how far, when the size is known. */
|
||||
@Composable
|
||||
internal fun Progress(now: Fetched.Loading) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
if (now.total > 0) CircularProgressIndicator(progress = { (now.done.toFloat() / now.total).coerceIn(0f, 1f) }) else CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A PDF's pages, drawn by the platform's own renderer from a copy in the private cache. One page
|
||||
* is open at a time, and at most [PDF_MAX_PAGES] are offered. The renderer cannot be stopped in
|
||||
* the middle of a page, and closing it waits for the page being drawn: so [close] is never
|
||||
* called on the main thread -- [closeLater] is.
|
||||
*/
|
||||
class PdfPages(private val copy: File) {
|
||||
private val descriptor = ParcelFileDescriptor.open(copy, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||
private val renderer = try {
|
||||
PdfRenderer(descriptor)
|
||||
} catch (e: Throwable) {
|
||||
descriptor.close()
|
||||
throw e
|
||||
}
|
||||
|
||||
/** Set before the lock is asked for: a page not yet begun is not begun any more. */
|
||||
@Volatile
|
||||
private var closing = false
|
||||
private var closed = false
|
||||
val count: Int = renderer.pageCount.coerceAtMost(PDF_MAX_PAGES)
|
||||
|
||||
/** Page [index] as pixels [width] wide; null once closed or when it cannot be drawn. */
|
||||
fun page(index: Int, width: Int): ImageBitmap? {
|
||||
if (closing || index !in 0 until count || width <= 0) return null
|
||||
return synchronized(this) {
|
||||
if (closed || closing) return@synchronized null
|
||||
runCatching {
|
||||
renderer.openPage(index).use { page ->
|
||||
var w = width
|
||||
var h = (page.height.toLong() * w / page.width.coerceAtLeast(1)).toInt().coerceAtLeast(1)
|
||||
// A page of an odd shape (a long receipt) is drawn smaller rather than as a huge bitmap.
|
||||
while (w.toLong() * h > PAGE_MAX_PIXELS) {
|
||||
w /= 2
|
||||
h /= 2
|
||||
}
|
||||
val bitmap = Bitmap.createBitmap(w.coerceAtLeast(1), h.coerceAtLeast(1), Bitmap.Config.ARGB_8888)
|
||||
// The paper: a PDF draws on transparent, and print is read on white in either theme.
|
||||
bitmap.eraseColor(PAPER)
|
||||
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
|
||||
bitmap.asImageBitmap()
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/** Lets go of the renderer, the descriptor and the copy, after the page being drawn. Blocks for that long. */
|
||||
fun close() {
|
||||
closing = true
|
||||
synchronized(this) {
|
||||
if (closed) return
|
||||
closed = true
|
||||
runCatching { renderer.close() }
|
||||
runCatching { descriptor.close() }
|
||||
copy.delete()
|
||||
}
|
||||
}
|
||||
|
||||
/** [close] from the main thread: no page is begun from now on, and the rest happens on a thread of its own. */
|
||||
fun closeLater() {
|
||||
closing = true
|
||||
Thread({ close() }, "pdf-close").start()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val PAGE_MAX_PIXELS = 6_000_000L
|
||||
const val PAPER = android.graphics.Color.WHITE
|
||||
}
|
||||
}
|
||||
|
||||
/** A PDF of the tree, page by page, as wide as the screen. */
|
||||
@Composable
|
||||
fun PdfBody(path: String, name: String, size: Long, fallback: @Composable (String?) -> Unit) =
|
||||
PdfBody(Raw.Path(path), name, size, gone = null, fallback = fallback)
|
||||
|
||||
/**
|
||||
* The same for any [Raw]: a file a chat names by its node id is copied and laid out as one of
|
||||
* the tree is. [gone] is what to say of a file that is no longer there, where the instance's own
|
||||
* refusal would name an id.
|
||||
*/
|
||||
@Composable
|
||||
fun PdfBody(what: Raw, name: String, size: Long, gone: String? = null, fallback: @Composable (String?) -> Unit) {
|
||||
val path = what
|
||||
val context = LocalContext.current
|
||||
var pages by remember(path) { mutableStateOf<Fetched<PdfPages>>(Fetched.Loading()) }
|
||||
DisposableEffect(path) {
|
||||
// Back during a slow page must not wait for it: the closing is not done on this thread.
|
||||
onDispose { (pages as? Fetched.Ready)?.value?.closeLater() }
|
||||
}
|
||||
LaunchedEffect(path) {
|
||||
if (size > PDF_MAX_BYTES) {
|
||||
pages = Fetched.Failed(null)
|
||||
return@LaunchedEffect
|
||||
}
|
||||
val copy = FileCache.viewing(context, name)
|
||||
// Held here too: a viewer closed while the renderer is being made never sees it in `pages`.
|
||||
var made: PdfPages? = null
|
||||
pages = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
context.lembas.gate.pass()
|
||||
api.copyInto(api.raw(what), copy, PDF_MAX_BYTES, stepped { done, total -> pages = Fetched.Loading(done, total) })
|
||||
withContext(Dispatchers.IO) { made = PdfPages(copy) }
|
||||
Fetched.Ready(checkNotNull(made))
|
||||
} catch (e: CancellationException) {
|
||||
made?.closeLater()
|
||||
copy.delete()
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
made?.closeLater()
|
||||
copy.delete()
|
||||
// A password, or not a PDF after all: the renderer's own words are for a developer.
|
||||
Fetched.Failed(
|
||||
when {
|
||||
gone != null && e is ApiException && e.status == 404 -> gone
|
||||
e is ApiException || unreachable(e) -> viewerSays(context, e)
|
||||
else -> null
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
when (val now = pages) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> fallback(now.message)
|
||||
is Fetched.Ready -> PdfPagesList(now.value)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PdfPagesList(pages: PdfPages) {
|
||||
val palette = LocalPalette.current
|
||||
val list = rememberLazyListState()
|
||||
// Read through a derived state: the line is drawn again when the page changes, not at every pixel of a scroll.
|
||||
val first by remember { derivedStateOf { list.firstVisibleItemIndex + 1 } }
|
||||
Column(Modifier.fillMaxSize().background(palette.bgSunken)) {
|
||||
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
|
||||
val width = with(LocalDensity.current) { maxWidth.toPx() }.toInt().coerceIn(1, 1600)
|
||||
LazyColumn(
|
||||
state = list,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
items(pages.count) { index ->
|
||||
val page by produceState<ImageBitmap?>(null, pages, index, width) {
|
||||
value = withContext(Dispatchers.Default) { pages.page(index, width) }
|
||||
}
|
||||
val drawn = page
|
||||
if (drawn != null) {
|
||||
Image(drawn, contentDescription = null, contentScale = ContentScale.FillWidth, modifier = Modifier.fillMaxWidth())
|
||||
} else {
|
||||
// Until it is drawn: a sheet of the usual shape, so the list does not jump far.
|
||||
Box(Modifier.fillMaxWidth().aspectRatio(0.707f).background(palette.surfaceRaised))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.viewer_page, first.toString(), pages.count.toString()),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.fillMaxWidth().background(palette.bg).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A file on the instance as the platform's player reads it: piece by piece, each a `Range`
|
||||
* request made by the app's own HTTP client with the token in its header. The player is never
|
||||
* given an address, so the token is never in one. [what] is a file by its path or by its node
|
||||
* id (what a generated file's result carries).
|
||||
*/
|
||||
class RemoteMedia(api: ApiClient, what: Raw, private val length: Long) : MediaDataSource() {
|
||||
private val reader = RangeReader(length) { from, to -> api.rawBytes(what, from, to) }
|
||||
|
||||
override fun readAt(position: Long, buffer: ByteArray, offset: Int, size: Int): Int = reader.read(position, buffer, offset, size)
|
||||
|
||||
override fun getSize(): Long = length
|
||||
|
||||
override fun close() = reader.close()
|
||||
}
|
||||
|
||||
/** The most a chat's attachment may weigh to be copied for the player. */
|
||||
const val ATTACHED_MAX_BYTES = 512L * 1024 * 1024
|
||||
|
||||
/**
|
||||
* Sound or video, played by the platform's player. A file of the tree ([Raw.Path], [Raw.Node])
|
||||
* is streamed: it starts before the file is there, and seeking asks for the piece it lands in.
|
||||
* A chat's attachment ([Raw.Attached]) is answered whole by the instance, so it is copied into
|
||||
* the private cache first and played from there; the copy goes when the player does. Leaving
|
||||
* the app pauses it; leaving the viewer lets go of it.
|
||||
*/
|
||||
@Composable
|
||||
fun MediaBody(what: Raw, size: Long, video: Boolean, fallback: @Composable (String?) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var ui by remember(what) { mutableStateOf(PlayerUi()) }
|
||||
var failed by remember(what) { mutableStateOf(false) }
|
||||
var said by remember(what) { mutableStateOf<String?>(null) }
|
||||
var player by remember(what) { mutableStateOf<MediaPlayer?>(null) }
|
||||
var surface by remember(what) { mutableStateOf<SurfaceHolder?>(null) }
|
||||
var ratio by remember(what) { mutableStateOf(16f / 9f) }
|
||||
|
||||
DisposableEffect(what) {
|
||||
var held: MediaPlayer? = null
|
||||
var source: RemoteMedia? = null
|
||||
var copy: File? = null
|
||||
val starting = scope.launch {
|
||||
val api = context.lembas.instances.client()
|
||||
if (api == null || (size <= 0 && what !is Raw.Attached)) {
|
||||
failed = true
|
||||
return@launch
|
||||
}
|
||||
try {
|
||||
val made = MediaPlayer().also { held = it }
|
||||
made.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(if (video) AudioAttributes.CONTENT_TYPE_MOVIE else AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||
.build(),
|
||||
)
|
||||
if (what is Raw.Attached) {
|
||||
val local = FileCache.viewing(context, "attachment").also { copy = it }
|
||||
// A copy is a request with the account's file in it: not while the phone is locked.
|
||||
context.lembas.gate.pass()
|
||||
api.copyInto(api.raw(what), local, ATTACHED_MAX_BYTES)
|
||||
made.setDataSource(local.path)
|
||||
} else {
|
||||
made.setDataSource(RemoteMedia(api, what, size).also { source = it })
|
||||
}
|
||||
made.setOnPreparedListener {
|
||||
ui = ui.copy(ready = true, durationMs = it.duration.coerceAtLeast(0))
|
||||
player = it
|
||||
}
|
||||
made.setOnCompletionListener { ui = ui.copy(playing = false, positionMs = ui.durationMs) }
|
||||
made.setOnErrorListener { _, _, _ ->
|
||||
failed = true
|
||||
true
|
||||
}
|
||||
made.setOnVideoSizeChangedListener { _, w, h -> if (w > 0 && h > 0) ratio = (w.toFloat() / h).coerceIn(0.3f, 4f) }
|
||||
made.prepareAsync()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// The instance's refusal of a copy is a sentence to read; the player's own failure is not.
|
||||
said = if (e is ApiException || unreachable(e)) viewerSays(context, e) else null
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
onDispose {
|
||||
starting.cancel()
|
||||
player = null
|
||||
held?.runCatching { release() }
|
||||
source?.runCatching { close() }
|
||||
copy?.runCatching { delete() }
|
||||
}
|
||||
}
|
||||
|
||||
// The picture goes where the surface is, for as long as there is one.
|
||||
LaunchedEffect(player, surface) { player?.runCatching { setDisplay(surface) } }
|
||||
LaunchedEffect(player, ui.playing) {
|
||||
while (ui.playing) {
|
||||
player?.runCatching { currentPosition }?.getOrNull()?.let { ui = ui.copy(positionMs = it) }
|
||||
delay(500)
|
||||
}
|
||||
}
|
||||
LifecycleEventEffect(Lifecycle.Event.ON_STOP) {
|
||||
player?.runCatching { if (isPlaying) pause() }
|
||||
ui = ui.copy(playing = false)
|
||||
}
|
||||
|
||||
if (failed) {
|
||||
fallback(said)
|
||||
return
|
||||
}
|
||||
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
if (video) {
|
||||
AndroidView(
|
||||
factory = { viewContext ->
|
||||
SurfaceView(viewContext).apply {
|
||||
holder.addCallback(
|
||||
object : SurfaceHolder.Callback {
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
surface = holder
|
||||
}
|
||||
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
player?.runCatching { setDisplay(null) }
|
||||
surface = null
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().weight(1f, fill = false).aspectRatio(ratio),
|
||||
)
|
||||
} else {
|
||||
Icon(Icons.Filled.MusicNote, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.padding(24.dp).size(72.dp))
|
||||
}
|
||||
PlayerControls(
|
||||
ui,
|
||||
onToggle = {
|
||||
val now = player ?: return@PlayerControls
|
||||
runCatching {
|
||||
if (now.isPlaying) {
|
||||
now.pause()
|
||||
ui = ui.copy(playing = false)
|
||||
} else {
|
||||
if (ui.durationMs > 0 && ui.positionMs >= ui.durationMs) now.seekTo(0)
|
||||
now.start()
|
||||
ui = ui.copy(playing = true)
|
||||
}
|
||||
}
|
||||
},
|
||||
onSeek = { to ->
|
||||
player?.runCatching { seekTo(to) }
|
||||
ui = ui.copy(positionMs = to)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** What a player opened over a chat plays: which bytes, what it is called, how large, and whether there is a picture. */
|
||||
data class Playing(val what: Raw, val title: String, val size: Long, val video: Boolean)
|
||||
|
||||
/** A document a chat names, to be laid out over it: a PDF an agent showed. */
|
||||
data class Reading(val what: Raw, val title: String, val size: Long)
|
||||
|
||||
/**
|
||||
* A PDF over the whole screen, for a file a chat names by its node id: its pages as the tree's
|
||||
* viewer lays them out, from a copy in the private cache. One that is no longer there says so
|
||||
* ([gone]); one this phone cannot lay out says that it can still be downloaded. Back or the cross
|
||||
* closes it.
|
||||
*/
|
||||
@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun DocumentDialog(reading: Reading, onClose: () -> Unit, gone: String) {
|
||||
val palette = LocalPalette.current
|
||||
val unreadable: @Composable (String?) -> Unit = { note ->
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(note ?: stringResource(R.string.files_not_shown), color = palette.inkMuted, modifier = Modifier.padding(32.dp))
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = { Text(reading.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
PdfBody(reading.what, reading.title, reading.size, gone = gone, fallback = unreadable)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How a player's file was found before it was handed to the player. */
|
||||
private sealed interface Probed {
|
||||
data object Asking : Probed
|
||||
|
||||
data object There : Probed
|
||||
|
||||
data class Refused(val message: String?) : Probed
|
||||
}
|
||||
|
||||
/**
|
||||
* A player over the whole screen, for a file a chat names: a generated video or track (by its
|
||||
* node id) or an attachment. A file of the tree is asked for its first byte before the player
|
||||
* gets it, so one that is no longer there says so in a sentence rather than as a player that
|
||||
* does not start. Back or the cross closes it and lets go of the player.
|
||||
*/
|
||||
@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun PlayerDialog(playing: Playing, onClose: () -> Unit, gone: String) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val probed by produceState<Probed>(Probed.Asking, playing.what) {
|
||||
if (playing.what is Raw.Attached) {
|
||||
value = Probed.There
|
||||
return@produceState
|
||||
}
|
||||
value = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
context.lembas.gate.pass()
|
||||
withContext(Dispatchers.IO) { api.rawBytes(playing.what, 0, 0) }
|
||||
Probed.There
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// By its id the instance's own refusal names the id; "no longer there" is what a person reads.
|
||||
Probed.Refused(if (e is ApiException && e.status == 404) gone else viewerSays(context, e))
|
||||
}
|
||||
}
|
||||
val unplayable: @Composable (String?) -> Unit = { note ->
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(note ?: stringResource(R.string.files_not_shown), color = palette.inkMuted, modifier = Modifier.padding(32.dp))
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = { Text(playing.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when (val now = probed) {
|
||||
Probed.Asking -> Progress(Fetched.Loading())
|
||||
is Probed.Refused -> unplayable(now.message)
|
||||
Probed.There -> MediaBody(playing.what, playing.size, playing.video, unplayable)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.viewer
|
||||
|
||||
import android.content.Context
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileContent
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileView
|
||||
import eu.llembas.android.api.Notebook
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.SaveConflict
|
||||
import eu.llembas.android.api.Table
|
||||
import eu.llembas.android.api.parseNotebook
|
||||
import eu.llembas.android.api.parseTable
|
||||
import eu.llembas.android.api.tableDelimiter
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.files.CreateFile
|
||||
import eu.llembas.android.ui.files.SaidDialog
|
||||
import eu.llembas.android.ui.files.TransferHost
|
||||
import eu.llembas.android.ui.files.TransferViewModel
|
||||
import eu.llembas.android.ui.files.VersionsDialog
|
||||
import eu.llembas.android.ui.files.filesSay
|
||||
import eu.llembas.android.ui.files.noSuchRoute
|
||||
import eu.llembas.android.ui.files.rememberSaver
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** What a viewer says of a failure: the server's or the network's sentence; null for "too large for this phone". */
|
||||
internal fun viewerSays(context: Context, e: Throwable): String? {
|
||||
val tooLarge = e is ApiException && e.status == 413 && e.message.isNullOrBlank()
|
||||
return if (tooLarge) null else context.explain(e)
|
||||
}
|
||||
|
||||
/**
|
||||
* The text being edited, kept apart from the screen: a megabyte does not fit what Android saves
|
||||
* of a screen when the phone is turned, and unsaved words must not go with it. [draft] is null
|
||||
* while nothing is edited; [touched] once a key was pressed.
|
||||
*/
|
||||
class EditViewModel : ViewModel() {
|
||||
var draft by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var touched by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** The `sha` the text had when it was read: a save says it, so somebody else's change is not written over. */
|
||||
var base: String = ""
|
||||
private set
|
||||
|
||||
fun start(text: String, sha: String) {
|
||||
draft = text
|
||||
base = sha
|
||||
touched = false
|
||||
}
|
||||
|
||||
fun type(text: String) {
|
||||
draft = text
|
||||
touched = true
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
draft = null
|
||||
touched = false
|
||||
}
|
||||
}
|
||||
|
||||
/** A file of the tree, opened: on its way, not to be had, or what the server says of it. */
|
||||
private sealed interface Opened {
|
||||
data object Loading : Opened
|
||||
|
||||
data class Failed(val message: String) : Opened
|
||||
|
||||
data class Ready(val file: FileContent) : Opened
|
||||
}
|
||||
|
||||
/**
|
||||
* A file of the person's tree, full screen, drawn by what the server says it is (`file_kind`):
|
||||
* text kinds as text (and edited as text), a picture, a PDF's pages, sound and video streamed, a
|
||||
* table's grid, a notebook's cells, and for the rest what it is with Download, Open with and
|
||||
* Share. The person's own files are no more trusted than a model's, since a model may have
|
||||
* written them: **nothing is rendered as HTML and nothing a file holds is run** -- an HTML page
|
||||
* and an SVG are their source. [onChanged]: the file was saved or a version restored, so a
|
||||
* listing behind this is stale.
|
||||
*/
|
||||
@Composable
|
||||
fun TreeFileViewer(path: String, onClose: () -> Unit, startEditing: Boolean = false, onChanged: () -> Unit = {}) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val edit: EditViewModel = viewModel(key = "edit:$path")
|
||||
// Its own, not the Files page's: two hosts of one would each open the other app.
|
||||
val transfers: TransferViewModel = viewModel(key = "viewer-transfers")
|
||||
var opened by remember(path) { mutableStateOf<Opened>(Opened.Loading) }
|
||||
var reads by remember(path) { mutableIntStateOf(0) }
|
||||
var web by remember(path) { mutableStateOf<String?>(null) }
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var versions by remember { mutableStateOf(false) }
|
||||
var leaving by remember { mutableStateOf(false) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var conflict by remember { mutableStateOf<String?>(null) }
|
||||
var said by remember { mutableStateOf<String?>(null) }
|
||||
var wantsEdit by remember(path) { mutableStateOf(startEditing) }
|
||||
// A table can be read as the text it is, as well as laid out.
|
||||
var tableAsText by remember(path) { mutableStateOf(false) }
|
||||
val saveVersion = rememberSaver(transfers)
|
||||
val name = FileKinds.name(path)
|
||||
|
||||
LaunchedEffect(path, reads) {
|
||||
val api = context.lembas.instances.client()
|
||||
if (api == null) {
|
||||
opened = Opened.Failed(context.getString(R.string.assist_signed_out))
|
||||
return@LaunchedEffect
|
||||
}
|
||||
web = api.webFile(path)
|
||||
opened = try {
|
||||
val file = api.fileContent(path)
|
||||
// A new file opens ready to be written in; so does one whose text was read again after a conflict.
|
||||
if (wantsEdit && FileKinds.editable(file.fileKind, file.writable, file.withheld != null)) edit.start(file.text, file.sha)
|
||||
wantsEdit = false
|
||||
Opened.Ready(file)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Opened.Failed(context.filesSay(e))
|
||||
}
|
||||
}
|
||||
|
||||
val file = (opened as? Opened.Ready)?.file
|
||||
val draft = edit.draft
|
||||
val saveTo = rememberLauncherForActivityResult(CreateFile()) { to -> if (to != null) transfers.download(listOf(path), zip = false, to = to) }
|
||||
val actions = remember(path, file?.mime) {
|
||||
object : FileActions {
|
||||
override fun download() = saveTo.launch(CreateFile.Ask(name, file?.mime.orEmpty()))
|
||||
|
||||
override fun openWith() = transfers.openWith(path, name)
|
||||
|
||||
override fun share() = transfers.share(listOf(FileEntry(name = name, path = path, mime = file?.mime.orEmpty())))
|
||||
}
|
||||
}
|
||||
|
||||
fun save(force: Boolean) {
|
||||
val text = edit.draft ?: return
|
||||
saving = true
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
val saved = api.saveFile(path, text, base = edit.base, force = force)
|
||||
edit.stop()
|
||||
opened = Opened.Ready(saved)
|
||||
onChanged()
|
||||
} catch (e: SaveConflict) {
|
||||
// Nothing was written. The server's sentence, with the two ways on.
|
||||
conflict = e.message?.ifBlank { null } ?: context.getString(R.string.files_conflict)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
said = context.filesSay(e)
|
||||
} finally {
|
||||
saving = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Leaving with words that were not saved asks first: Back, the cross, and a tap outside all come here.
|
||||
fun close() {
|
||||
when {
|
||||
draft != null && edit.touched -> leaving = true
|
||||
draft != null -> edit.stop()
|
||||
else -> onClose()
|
||||
}
|
||||
}
|
||||
|
||||
Dialog(onDismissRequest = { close() }, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = { close() }) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = {
|
||||
Column {
|
||||
Text(name, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (draft != null) {
|
||||
IconButton(onClick = { save(force = false) }, enabled = !saving && edit.touched) {
|
||||
Icon(Icons.Filled.Check, contentDescription = stringResource(R.string.save))
|
||||
}
|
||||
} else if (file != null) {
|
||||
if (FileKinds.editable(file.fileKind, file.writable, file.withheld != null)) {
|
||||
IconButton(onClick = {
|
||||
edit.start(file.text, file.sha)
|
||||
}) { Icon(Icons.Filled.Edit, contentDescription = stringResource(R.string.edit)) }
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { menu = true }) { Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more)) }
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
val then: (() -> Unit) -> (() -> Unit) = { act ->
|
||||
{
|
||||
menu = false
|
||||
act()
|
||||
}
|
||||
}
|
||||
val text = file.text.takeIf { file.withheld == null && it.isNotEmpty() }
|
||||
if (text != null) MenuEntry(R.string.viewer_copy, then { copy(context, name, text) })
|
||||
if (text != null && FileKinds.viewer(file.fileKind) == FileView.Table) {
|
||||
MenuEntry(if (tableAsText) R.string.table_as_table else R.string.table_as_text, then { tableAsText = !tableAsText })
|
||||
}
|
||||
if (file.fileKind != null) {
|
||||
MenuEntry(R.string.download, then { actions.download() })
|
||||
MenuEntry(R.string.files_open_with, then { actions.openWith() })
|
||||
MenuEntry(R.string.report_share, then { actions.share() })
|
||||
MenuEntry(R.string.versions, then { versions = true })
|
||||
}
|
||||
web?.let { url -> MenuEntry(R.string.viewer_open_browser, then { openOutside(context, url) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
if (saving) LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp))
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
when (val now = opened) {
|
||||
Opened.Loading -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
is Opened.Failed -> Text(now.message, color = palette.inkMuted, modifier = Modifier.align(Alignment.Center).padding(32.dp))
|
||||
is Opened.Ready -> if (draft != null) EditorBody(draft, edit::type, enabled = !saving) else Shown(path, now.file, actions, tableAsText)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (leaving) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { leaving = false },
|
||||
text = { Text(stringResource(R.string.files_unsaved)) },
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
leaving = false
|
||||
edit.stop()
|
||||
},
|
||||
) { Text(stringResource(R.string.discard)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { leaving = false }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
conflict?.let { sentence ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { conflict = null },
|
||||
text = { Text(sentence) },
|
||||
// Two ways on, and neither is the default: the words stack, so each is a whole row.
|
||||
confirmButton = {
|
||||
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.End) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
conflict = null
|
||||
// What the file holds now, in place of what was typed here.
|
||||
edit.stop()
|
||||
wantsEdit = true
|
||||
reads++
|
||||
},
|
||||
) { Text(stringResource(R.string.reload)) }
|
||||
TextButton(
|
||||
onClick = {
|
||||
conflict = null
|
||||
save(force = true)
|
||||
},
|
||||
) { Text(stringResource(R.string.files_save_anyway)) }
|
||||
TextButton(onClick = { conflict = null }) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
said?.let { SaidDialog(it, onClose = { said = null }) }
|
||||
if (versions) {
|
||||
VersionsDialog(
|
||||
path,
|
||||
onDownload = { version -> saveVersion(Raw.Path(path, version.id), name, file?.mime.orEmpty()) },
|
||||
onClose = { versions = false },
|
||||
onRestored = {
|
||||
versions = false
|
||||
reads++
|
||||
onChanged()
|
||||
},
|
||||
)
|
||||
}
|
||||
TransferHost(transfers)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MenuEntry(label: Int, onClick: () -> Unit) = DropdownMenuItem(text = { Text(stringResource(label)) }, onClick = onClick)
|
||||
|
||||
/** A file that was read, by its kind. What cannot be drawn falls back to the details page, saying why. */
|
||||
@Composable
|
||||
private fun Shown(path: String, file: FileContent, actions: FileActions, tableAsText: Boolean = false) {
|
||||
val context = LocalContext.current
|
||||
val name = file.name.ifBlank { FileKinds.name(path) }
|
||||
val type = listOf(file.fileKind.orEmpty(), file.mime).filter { it.isNotBlank() }.joinToString(" · ")
|
||||
val details: @Composable (String?) -> Unit = { note -> DetailsBody(name, type, file.size, note ?: stringResource(R.string.files_not_shown), actions) }
|
||||
val withheld = file.withheld
|
||||
when (FileKinds.viewer(file.fileKind)) {
|
||||
FileView.Text -> when {
|
||||
withheld != null -> {
|
||||
val why = if (withheld.reason == "too_large") R.string.viewer_too_large else R.string.viewer_not_text
|
||||
details(withheld.message.ifBlank { stringResource(why) })
|
||||
}
|
||||
|
||||
file.fileKind == "svg" -> Column(Modifier.fillMaxSize()) {
|
||||
Note(stringResource(R.string.files_svg_source))
|
||||
FileBody("code", "xml", 0, file.text)
|
||||
}
|
||||
|
||||
else -> FileBody(file.viewKind, file.language, 0, file.text)
|
||||
}
|
||||
|
||||
FileView.Image -> ImageBody(path, name, file.size, details)
|
||||
|
||||
FileView.Pdf -> PdfBody(path, name, file.size, details)
|
||||
|
||||
FileView.Audio -> MediaBody(Raw.Path(path), file.size, video = false, fallback = details)
|
||||
|
||||
FileView.Video -> MediaBody(Raw.Path(path), file.size, video = true, fallback = details)
|
||||
|
||||
FileView.Table -> if (tableAsText && withheld == null) {
|
||||
FileBody("text", "", 0, file.text)
|
||||
} else {
|
||||
val table by produceState<Fetched<Table>>(Fetched.Loading(), path, file.sha) {
|
||||
value = try {
|
||||
// Up to 1 MB the server sent the text; of a longer table the first megabyte is asked for.
|
||||
val text = if (withheld == null) {
|
||||
file.text
|
||||
} else {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
withContext(Dispatchers.IO) { api.rawBytes(path, 0, TABLE_HEAD - 1).toString(Charsets.UTF_8) }
|
||||
}
|
||||
Fetched.Ready(withContext(Dispatchers.Default) { parseTable(text, tableDelimiter(name, text), partial = withheld != null) })
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Fetched.Failed(if (noSuchRoute(e)) null else viewerSays(context, e))
|
||||
}
|
||||
}
|
||||
when (val now = table) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> details(now.message)
|
||||
is Fetched.Ready -> if (now.value.rows.isEmpty()) FileBody("text", "", 0, file.text) else TableBody(now.value)
|
||||
}
|
||||
}
|
||||
|
||||
FileView.Notebook -> {
|
||||
// Up to a megabyte of JSON: read off the main thread, not while the page is being drawn.
|
||||
val notebook by produceState<Fetched<Notebook>>(Fetched.Loading(), file.sha, file.text) {
|
||||
val parsed = if (withheld == null) withContext(Dispatchers.Default) { parseNotebook(file.text) } else null
|
||||
value = if (parsed != null) Fetched.Ready(parsed) else Fetched.Failed(withheld?.message?.ifBlank { null })
|
||||
}
|
||||
when (val now = notebook) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> details(now.message)
|
||||
is Fetched.Ready -> NotebookBody(now.value)
|
||||
}
|
||||
}
|
||||
|
||||
FileView.Details -> {
|
||||
val archive = file.archive
|
||||
when {
|
||||
// An instance that lists what the archive holds: the names, as text, and nothing unpacked.
|
||||
archive != null && archive.problem == null -> ArchiveBody(archive, actions)
|
||||
|
||||
archive != null -> details(archive.message.ifBlank { stringResource(R.string.archive_unreadable) })
|
||||
|
||||
else -> details(stringResource(if (file.fileKind == "archive") R.string.archive_note else R.string.files_no_viewer))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How much of a table too long to be sent as text is read for its first rows. */
|
||||
private const val TABLE_HEAD = 1024L * 1024
|
||||
@@ -10,9 +10,12 @@ import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.AppRelease
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.SharedHttp
|
||||
import eu.llembas.android.api.await
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.notify.NotificationAccess
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.Serializable
|
||||
@@ -20,9 +23,34 @@ import okhttp3.Request
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** What llembas.eu says the newest release is (`site/android/latest.json`, written at release). */
|
||||
/** One APK of a release: where it is and its SHA-256. */
|
||||
@Serializable
|
||||
data class Latest(val version: String, val url: String, val sha256: String, val notes: String = "")
|
||||
data class LatestFile(val url: String, val sha256: String)
|
||||
|
||||
/**
|
||||
* What llembas.eu says the newest release is (`site/android/latest.json`, written at release):
|
||||
* the standard APK as [url] and [sha256], and the `notifications` build's (the same app with the
|
||||
* notification listener) as [notifications] when the release has one.
|
||||
*/
|
||||
@Serializable
|
||||
data class Latest(val version: String, val url: String, val sha256: String, val notes: String = "", val notifications: LatestFile? = null) {
|
||||
/**
|
||||
* The file this build updates itself to: its own kind, never the other. A `notifications`
|
||||
* build that installed the standard APK would lose its listener without a word (same id,
|
||||
* same key: Android takes it), so without its own file it installs nothing.
|
||||
*/
|
||||
fun fileFor(notificationsBuild: Boolean): LatestFile? = if (notificationsBuild) notifications else LatestFile(url, sha256)
|
||||
|
||||
/**
|
||||
* The same, with what the instance says of the release it recommends (`GET /api/v2/apps`,
|
||||
* its entry's `notifications` build) for a manifest that names no notifications file -- but
|
||||
* only when both speak of the same version, and the address is https.
|
||||
*/
|
||||
fun fileFor(notificationsBuild: Boolean, recommended: AppRelease?): LatestFile? = fileFor(notificationsBuild)
|
||||
?: recommended?.takeIf { notificationsBuild && it.version == version }?.notifications
|
||||
?.takeIf { it.url.startsWith("https://") && it.sha256.isNotBlank() }
|
||||
?.let { LatestFile(it.url, it.sha256) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The `full` build updates itself, as LLeMbas Desktop does: the manifest on the website names
|
||||
@@ -47,12 +75,20 @@ class Updater(private val context: Context) {
|
||||
)
|
||||
return@withContext context.getString(R.string.update_allow_installs)
|
||||
}
|
||||
// Its own kind: from the manifest, else from the instance's recommendation of the same release.
|
||||
val recommended = if (NotificationAccess.AVAILABLE && latest.notifications == null) {
|
||||
runCatching { context.lembas.instances.client()?.apps()?.android }.getOrNull()
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val file = latest.fileFor(NotificationAccess.AVAILABLE, recommended)
|
||||
?: return@withContext context.getString(R.string.update_notifications_manual)
|
||||
val apk = File(context.cacheDir, "update.apk")
|
||||
SharedHttp.newCall(Request.Builder().url(latest.url).build()).await().use { response ->
|
||||
SharedHttp.newCall(Request.Builder().url(file.url).build()).await().use { response ->
|
||||
if (!response.isSuccessful) return@withContext context.getString(R.string.update_unreachable)
|
||||
apk.outputStream().use { out -> response.body!!.byteStream().copyTo(out) }
|
||||
}
|
||||
if (sha256(apk) != latest.sha256.lowercase()) {
|
||||
if (sha256(apk) != file.sha256.lowercase()) {
|
||||
apk.delete()
|
||||
return@withContext context.getString(R.string.update_bad_file)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import android.content.Context
|
||||
import eu.llembas.android.R
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.time.Instant
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/** One word of a wake phrase: its [id], how it is written for the person, and its spelling in the model's [pieces]. */
|
||||
data class WakeWord(val id: String, val words: String, val pieces: String)
|
||||
|
||||
/**
|
||||
* A wake phrase: a greeting and a name ("Hey Assistant"). What the person says ([words]), the
|
||||
* engine's spelling of it ([tokens], the model's BPE pieces -- generated with its `bpe.model` by
|
||||
* `scripts/gen-wake-phrases.py`, since the phone has no tokenizer), and the [id] Settings keeps.
|
||||
*
|
||||
* Only words from [WakeWords] can be chosen: an open-vocabulary spotter hears any phrase it can
|
||||
* spell, but one it was never trained to hear (a made-up name) has to be repeated until it lands,
|
||||
* and a free text box would invite one that fires on every other sentence. English only: the
|
||||
* model is trained on English speech.
|
||||
*/
|
||||
data class WakePhrase(val greeting: WakeWord, val name: WakeWord) {
|
||||
val id: String get() = "${greeting.id}_${name.id}"
|
||||
val words: String get() = "${greeting.words} ${name.words}"
|
||||
val tokens: String get() = "${greeting.pieces} ${name.pieces}"
|
||||
}
|
||||
|
||||
object WakePhrases {
|
||||
/** "Hey Assistant". */
|
||||
val default: WakePhrase = WakePhrase(WakeWords.greetings.first { it.id == "hey" }, WakeWords.names.first { it.id == "assistant" })
|
||||
|
||||
val all: List<WakePhrase> = WakeWords.greetings.flatMap { greeting -> WakeWords.names.map { WakePhrase(greeting, it) } }
|
||||
|
||||
/**
|
||||
* The phrase Settings saved as [id] (`greeting_name`). An id that is no longer a phrase --
|
||||
* the "Lembas" ones of the first wake word, which the model could not hear -- is the default.
|
||||
*/
|
||||
fun byId(id: String): WakePhrase = all.firstOrNull { it.id == id } ?: default
|
||||
}
|
||||
|
||||
/**
|
||||
* How easily the phrase is taken as heard: Settings › Wake word › Sensitivity.
|
||||
*
|
||||
* The engine has two numbers per keyword (sherpa-onnx's keyword-spotting documentation): a
|
||||
* boosting score that keeps the phrase's path alive in the search ([boost], larger is easier),
|
||||
* and a trigger threshold, the least probability the heard pieces must reach ([threshold], 0 to
|
||||
* 1, lower is easier). Normal is the engine's own default threshold with the boost its
|
||||
* documentation uses for a two-word phrase; Low takes that documentation's stricter example
|
||||
* (0.35), High goes as far below the default as Low goes above it. Starting values: nobody has
|
||||
* measured them on a phone yet.
|
||||
*/
|
||||
enum class WakeSensitivity(val id: String, val boost: Float, val threshold: Float) {
|
||||
Low("low", 1.0f, 0.35f),
|
||||
Normal("normal", 1.5f, 0.25f),
|
||||
High("high", 2.0f, 0.15f),
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun byId(id: String): WakeSensitivity = entries.firstOrNull { it.id == id } ?: Normal
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The engine, as the service sees it: 16 kHz mono samples in, the phrase out when it was heard.
|
||||
* Everything happens on the phone; [accept] neither records nor sends anything.
|
||||
*/
|
||||
interface WakeDetector {
|
||||
/** Feed [samples] (-1..1); true when the wake word ended in them. */
|
||||
fun accept(samples: FloatArray): Boolean
|
||||
|
||||
fun release()
|
||||
}
|
||||
|
||||
/** The microphone, as the listener sees it: 16 kHz mono samples, already recording when it is made. */
|
||||
interface WakeMicrophone {
|
||||
/** Fill [into]; how many samples were read, or a negative number when the microphone failed. */
|
||||
fun read(into: ShortArray): Int
|
||||
|
||||
fun close()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the assistant's sheet is up -- the wake-word service lets go of the microphone while
|
||||
* it is, and takes it back once the sheet is gone. Counted, since the session and the activity
|
||||
* can overlap for a moment when one hands over to the other.
|
||||
*
|
||||
* The wake word's own hold is apart from the count: when the word is heard the microphone is
|
||||
* the sheet's for a few seconds ([holdFor]), whether or not a sheet then says it is up. It ends
|
||||
* by itself on a scope that outlives the service, so a service that is destroyed in those
|
||||
* seconds cannot leave the wake word "paused while the assistant is open" for good.
|
||||
*/
|
||||
object AssistPresence {
|
||||
private val sheets = MutableStateFlow(0)
|
||||
private val held = MutableStateFlow(0L)
|
||||
private val holds = AtomicLong(0)
|
||||
private val _open = MutableStateFlow(0)
|
||||
val open: StateFlow<Int> = _open.asStateFlow()
|
||||
|
||||
private val process = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
private fun count() {
|
||||
_open.value = sheets.value + if (held.value != 0L) 1 else 0
|
||||
}
|
||||
|
||||
fun shown() {
|
||||
sheets.update { it + 1 }
|
||||
count()
|
||||
}
|
||||
|
||||
fun hidden() {
|
||||
sheets.update { (it - 1).coerceAtLeast(0) }
|
||||
count()
|
||||
}
|
||||
|
||||
/** The word was heard: the microphone is the sheet's for [millis], then the hold lets go by itself. */
|
||||
fun holdFor(millis: Long, scope: CoroutineScope = process) {
|
||||
// Each hold has a number of its own, never used twice, so an old one cannot end a newer one.
|
||||
val mine = holds.incrementAndGet()
|
||||
held.value = mine
|
||||
count()
|
||||
scope.launch {
|
||||
try {
|
||||
delay(millis)
|
||||
} finally {
|
||||
// Only the newest hold lets go; an older one that ends later changes nothing.
|
||||
if (held.compareAndSet(mine, 0L)) count()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** No hold is left standing: the wake-word service starts from what the sheets say alone. */
|
||||
fun release() {
|
||||
held.value = 0L
|
||||
count()
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the app has an activity on screen: counted from every activity's start and stop (LembasApp). */
|
||||
object AppVisibility {
|
||||
private val started = AtomicInteger(0)
|
||||
val visible: Boolean get() = started.get() > 0
|
||||
|
||||
fun activityStarted() {
|
||||
started.incrementAndGet()
|
||||
}
|
||||
|
||||
fun activityStopped() {
|
||||
started.updateAndGet { (it - 1).coerceAtLeast(0) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Why listening for the wake word is paused, or [None]: what the notification and Settings say.
|
||||
* [Silent] is the one the listener finds out itself: the microphone is open but gives no sound at
|
||||
* all, which is what Android hands a background app while a call or another recorder has it, or
|
||||
* while the phone's microphone switch is off.
|
||||
*/
|
||||
enum class WakePause { None, ScreenOff, BatterySaver, Assistant, NoMicrophone, Silent }
|
||||
|
||||
/**
|
||||
* When the service listens, from what the phone is doing: never while the sheet is up (it has the
|
||||
* microphone), never in battery saver (the person asked the phone to spare power), and -- when
|
||||
* Settings says so, the default -- only while the screen is on.
|
||||
*/
|
||||
fun wakePause(screenOn: Boolean, screenOnly: Boolean, batterySaver: Boolean, sheetOpen: Boolean, micAllowed: Boolean): WakePause = when {
|
||||
!micAllowed -> WakePause.NoMicrophone
|
||||
sheetOpen -> WakePause.Assistant
|
||||
batterySaver -> WakePause.BatterySaver
|
||||
screenOnly && !screenOn -> WakePause.ScreenOff
|
||||
else -> WakePause.None
|
||||
}
|
||||
|
||||
/** What went wrong: this build has no engine, the model's files, the engine itself, or the microphone. */
|
||||
enum class WakeFailure { NoEngine, Model, Engine, Microphone }
|
||||
|
||||
/** A failure with its kind, so the notification and Settings can say it in plain words. */
|
||||
class WakeError(val why: WakeFailure, cause: Throwable? = null, message: String? = cause?.message) : Exception(message, cause) {
|
||||
/** The technical half, for Settings and the log: the exception's name and what it said. */
|
||||
val detail: String
|
||||
get() = listOfNotNull(cause?.javaClass?.simpleName, message?.takeIf { it.isNotBlank() }).joinToString(": ").take(DETAIL_MAX)
|
||||
|
||||
private companion object {
|
||||
const val DETAIL_MAX = 200
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the wake word is doing, the one truth the service, its notification and Settings all read
|
||||
* ([WakeStatus.state]). [Failed] carries the plain reason and the technical [Failed.detail];
|
||||
* nothing here is ever a guess from the settings alone.
|
||||
*/
|
||||
sealed interface WakeState {
|
||||
/** Not running: turned off, or the phone stopped the service. */
|
||||
data object Off : WakeState
|
||||
|
||||
/** Running, loading the engine. */
|
||||
data object Starting : WakeState
|
||||
|
||||
/** The microphone is open and the engine hears it, for these words. */
|
||||
data class Listening(val phrase: String) : WakeState
|
||||
|
||||
data class Paused(val why: WakePause) : WakeState
|
||||
|
||||
data class Failed(val why: WakeFailure, val detail: String = "") : WakeState
|
||||
}
|
||||
|
||||
/**
|
||||
* "Test the wake word" (Settings): until [until] (the phone's elapsed time, in ms) a heard phrase
|
||||
* is counted in [heard] instead of opening the assistant. A deadline, not a switch, so a test
|
||||
* nobody ends cannot leave the wake word deaf.
|
||||
*/
|
||||
data class WakeTrial(val until: Long = 0, val heard: Int = 0)
|
||||
|
||||
/**
|
||||
* The wake word's state for the whole process: written by the service, read by everything else.
|
||||
*
|
||||
* A service instance writes with the token [begin] gave it, and only the newest token's writes
|
||||
* count: an old instance on its way out (its loop ending after Settings turned the wake word off
|
||||
* and on again) cannot write its "off" over the new one's state.
|
||||
*/
|
||||
object WakeStatus {
|
||||
private val _state = MutableStateFlow<WakeState>(WakeState.Off)
|
||||
val state: StateFlow<WakeState> = _state.asStateFlow()
|
||||
|
||||
private val _trial = MutableStateFlow(WakeTrial())
|
||||
val trial: StateFlow<WakeTrial> = _trial.asStateFlow()
|
||||
|
||||
private val _retries = MutableStateFlow(0)
|
||||
|
||||
/** Counts up each time somebody asks for a retry now ([retryNow]). */
|
||||
val retries: StateFlow<Int> = _retries.asStateFlow()
|
||||
|
||||
private val generation = AtomicInteger(0)
|
||||
|
||||
/** A new writer takes over: its token, which makes every older one's writes count for nothing. */
|
||||
fun begin(): Int = generation.incrementAndGet()
|
||||
|
||||
/** [now], if [token] is still the newest writer's. */
|
||||
fun set(token: Int, now: WakeState) {
|
||||
synchronized(generation) {
|
||||
if (token == generation.get()) _state.value = now
|
||||
}
|
||||
}
|
||||
|
||||
/** [now], said by the app itself, outside any service instance: not started and why, turned off. */
|
||||
fun set(now: WakeState) {
|
||||
synchronized(generation) { _state.value = now }
|
||||
}
|
||||
|
||||
/** Try again now, instead of when the back-off says: the person tapped the failure. */
|
||||
fun retryNow() = _retries.update { it + 1 }
|
||||
|
||||
/** Start a test at [now]: the next [TRIAL_MS] of heard phrases are counted, not acted on. */
|
||||
fun startTrial(now: Long) {
|
||||
_trial.value = WakeTrial(until = now + TRIAL_MS)
|
||||
}
|
||||
|
||||
/** The phrase was heard at [now]: true when a test took it, so the assistant stays shut. */
|
||||
fun heardInTrial(now: Long): Boolean {
|
||||
var taken = false
|
||||
_trial.update { trial ->
|
||||
taken = now < trial.until
|
||||
if (taken) trial.copy(heard = trial.heard + 1) else trial
|
||||
}
|
||||
return taken
|
||||
}
|
||||
|
||||
const val TRIAL_MS = 10_000L
|
||||
}
|
||||
|
||||
/**
|
||||
* One [attempt] in plain words, a line each: when and for which phrase; what was tried and how it
|
||||
* went (Android's own words where it refused); what was done instead; and, where the assistant
|
||||
* could not be used, what Android had said of it -- whether LLeMbas held the role, and when the
|
||||
* service was connected and disconnected in this run of the app.
|
||||
*/
|
||||
fun wakeAttemptWords(context: Context, attempt: WakeAttempt, zone: ZoneId = ZoneId.systemDefault(), locale: Locale = Locale.getDefault()): List<String> {
|
||||
fun time(at: Long): String = DateTimeFormatter.ofPattern("EEE d MMM, HH:mm:ss", locale).format(Instant.ofEpochMilli(at).atZone(zone))
|
||||
val lines = mutableListOf("${time(attempt.at)} · “${attempt.phrase}”")
|
||||
lines += when (attempt.outcome) {
|
||||
WakeAttempt.OUT_OPENED -> context.getString(R.string.wake_out_opened)
|
||||
WakeAttempt.OUT_TESTED -> context.getString(R.string.wake_out_tested)
|
||||
WakeAttempt.OUT_NO_SHEET -> context.getString(R.string.wake_out_no_sheet)
|
||||
WakeAttempt.OUT_REFUSED -> context.getString(R.string.wake_out_refused, attempt.detail)
|
||||
else -> context.getString(R.string.wake_out_not_connected)
|
||||
}
|
||||
when (attempt.fallback) {
|
||||
WakeWay.Activity.id -> lines += context.getString(R.string.wake_out_activity)
|
||||
WakeWay.Notification.id -> lines += context.getString(R.string.wake_out_notification)
|
||||
}
|
||||
if (attempt.outcome == WakeAttempt.OUT_TESTED) return lines
|
||||
if (attempt.sheetMs >= 0) lines += context.getString(R.string.wake_sheet_ms, attempt.sheetMs.toString())
|
||||
if (attempt.outcome == WakeAttempt.OUT_OPENED) return lines
|
||||
// Why the assistant's own way was not there, from what Android itself said at that moment.
|
||||
lines += when {
|
||||
!attempt.assistant -> context.getString(R.string.wake_role_not_held)
|
||||
!attempt.recognizers -> context.getString(R.string.wake_no_recognizers)
|
||||
!attempt.active -> context.getString(R.string.wake_not_active)
|
||||
else -> context.getString(R.string.wake_role_held)
|
||||
}
|
||||
if (attempt.waited) lines += context.getString(R.string.wake_waited)
|
||||
if (attempt.showFailed) lines += context.getString(R.string.wake_show_failed)
|
||||
lines += if (attempt.readyAt == 0L) context.getString(R.string.wake_link_never) else context.getString(R.string.wake_link_ready, time(attempt.readyAt))
|
||||
if (attempt.shutdownAt != 0L) lines += context.getString(R.string.wake_link_shutdown, time(attempt.shutdownAt))
|
||||
if (attempt.connectedLater != 0L) lines += context.getString(R.string.wake_link_later, time(attempt.connectedLater))
|
||||
// The rest as it was noted, for whoever looks for the cause: names and values, not a sentence.
|
||||
lines += listOf(
|
||||
"screen=${if (attempt.screenOn) "on" else "off"}",
|
||||
"locked=${attempt.locked}",
|
||||
"visible=${attempt.visible}",
|
||||
"created=${if (attempt.createdAt == 0L) "-" else time(attempt.createdAt)}",
|
||||
"destroyed=${if (attempt.destroyedAt == 0L) "-" else time(attempt.destroyedAt)}",
|
||||
"prepared=${attempt.prepared}",
|
||||
).joinToString(" ")
|
||||
return lines
|
||||
}
|
||||
|
||||
/**
|
||||
* What the service's notification says the moment Android starts it (again): what is true --
|
||||
* [current], while its loop is [running]; "starting" for a service that has only just begun.
|
||||
* Never a phrase by default.
|
||||
*/
|
||||
fun wakeStateAtStart(running: Boolean, current: WakeState): WakeState = if (running && current != WakeState.Off) current else WakeState.Starting
|
||||
|
||||
/**
|
||||
* [state] in plain words: the notification's title and Settings' line. A failure names what
|
||||
* failed and that it is tried again; it never claims to listen while it does not.
|
||||
*/
|
||||
fun wakeTitle(context: Context, state: WakeState): String = when (state) {
|
||||
WakeState.Off -> context.getString(R.string.wake_off)
|
||||
|
||||
WakeState.Starting -> context.getString(R.string.wake_starting)
|
||||
|
||||
is WakeState.Listening -> context.getString(R.string.wake_listening_for, state.phrase)
|
||||
|
||||
is WakeState.Paused -> context.getString(
|
||||
when (state.why) {
|
||||
WakePause.None -> R.string.wake_starting
|
||||
WakePause.ScreenOff -> R.string.wake_paused_screen
|
||||
WakePause.BatterySaver -> R.string.wake_paused_battery
|
||||
WakePause.Assistant -> R.string.wake_paused_assistant
|
||||
WakePause.NoMicrophone -> R.string.wake_paused_microphone
|
||||
WakePause.Silent -> R.string.wake_paused_silent
|
||||
},
|
||||
)
|
||||
|
||||
is WakeState.Failed -> context.getString(
|
||||
when (state.why) {
|
||||
WakeFailure.NoEngine -> R.string.wake_failed_no_engine
|
||||
WakeFailure.Model -> R.string.wake_failed_model
|
||||
WakeFailure.Engine -> R.string.wake_failed_engine
|
||||
WakeFailure.Microphone -> R.string.wake_failed_microphone
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** The notification's second line: the promise while it listens, else nothing more to say. */
|
||||
fun wakeLine(context: Context, state: WakeState): String? = when (state) {
|
||||
is WakeState.Listening -> context.getString(R.string.wake_notification_line)
|
||||
is WakeState.Failed -> if (state.why == WakeFailure.NoEngine) null else context.getString(R.string.wake_failed_line)
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* The engine's keywords file for [phrase]: its pieces, `:` the boosting score, `#` the trigger
|
||||
* threshold, then `@` and the id the engine answers with (sherpa-onnx's syntax; no space after
|
||||
* `:` or `#`). A phrase of fewer than five pieces is short enough to turn up inside other speech,
|
||||
* so it has to be a little surer ([SHORT_PHRASE_STRICTER]).
|
||||
*/
|
||||
fun wakeKeywords(phrase: WakePhrase, sensitivity: WakeSensitivity = WakeSensitivity.Normal): String {
|
||||
val short = phrase.tokens.split(' ').size < SHORT_PHRASE_PIECES
|
||||
val threshold = sensitivity.threshold + if (short) SHORT_PHRASE_STRICTER else 0f
|
||||
// Locale.ROOT: a decimal comma would not be a number to the engine.
|
||||
return String.format(Locale.ROOT, "%s :%.1f #%.2f @%s\n", phrase.tokens, sensitivity.boost, threshold, phrase.id)
|
||||
}
|
||||
|
||||
private const val SHORT_PHRASE_PIECES = 5
|
||||
private const val SHORT_PHRASE_STRICTER = 0.05f
|
||||
|
||||
/**
|
||||
* Every piece of [keywords] must be in the model's token table ([tokens], `tokens.txt`: a piece
|
||||
* and its number per line): the engine ends the whole app on a piece it does not know, so it is
|
||||
* never handed one.
|
||||
*/
|
||||
fun checkKeywords(keywords: String, tokens: String) {
|
||||
val known = tokens.lineSequence().map { it.substringBeforeLast(' ') }.toSet()
|
||||
for (line in keywords.lineSequence().filter { it.isNotBlank() }) {
|
||||
val unknown = line.split(' ').filter { it.isNotEmpty() && it[0] !in ":#@" }.firstOrNull { it !in known }
|
||||
if (unknown != null) throw WakeError(WakeFailure.Engine, message = "the model has no piece \"$unknown\"")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The model's files, out of the APK's assets into [dir], where the engine reads them as files.
|
||||
* Copied by stream ([open] is `AssetManager.open`), so it works however the APK stores them, and
|
||||
* keyed by the assets' `version` (a hash of the pinned model, written by
|
||||
* `scripts/fetch-wakeword.py`): a new model replaces the old one, and a copy that was cut short
|
||||
* has no marker and is made again.
|
||||
*/
|
||||
fun unpackWakeModel(open: (String) -> InputStream, dir: File, files: List<String>) {
|
||||
val version = open("version").use { it.readBytes().decodeToString().trim() }
|
||||
val marker = File(dir, "version")
|
||||
if (marker.isFile && marker.readText() == version && files.all { File(dir, it).length() > 0 }) return
|
||||
if (!dir.isDirectory && !dir.mkdirs()) throw IOException("cannot make ${dir.name}")
|
||||
marker.delete()
|
||||
for (name in files) {
|
||||
val part = File(dir, "$name.part")
|
||||
open(name).use { input -> part.outputStream().use { input.copyTo(it) } }
|
||||
if (part.length() == 0L) throw IOException("$name is empty")
|
||||
val target = File(dir, name)
|
||||
target.delete()
|
||||
if (!part.renameTo(target)) throw IOException("cannot write $name")
|
||||
}
|
||||
marker.writeText(version)
|
||||
}
|
||||
|
||||
/** How long to wait before the next try after the [attempt]-th failure in a row: 2 s, 5 s, 15 s, 1 min, then every 5 min. */
|
||||
fun wakeBackoff(attempt: Int): Long = listOf(2_000L, 5_000L, 15_000L, 60_000L).getOrElse(attempt) { 300_000L }
|
||||
@@ -0,0 +1,207 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/** What the service wants right now: this phrase, spelled for the engine as [keywords], unless [pause]d. */
|
||||
data class WakePlan(val phrase: WakePhrase, val keywords: String, val pause: WakePause)
|
||||
|
||||
/**
|
||||
* The listening itself, apart from Android so it can be tested: follows the plans, keeps one
|
||||
* engine and one microphone, and says every change of state through [say].
|
||||
*
|
||||
* Nothing fails silently. An engine that does not load, a microphone that does not start or
|
||||
* stops giving samples: each is a [WakeState.Failed] with its reason, logged, and tried again
|
||||
* after [backoff]. And the engine is never released while a loop may still be feeding it: a new
|
||||
* plan first cancels the old loop and waits for it to end ([cancelAndJoin]), then the engine is
|
||||
* swapped, on the one coroutine that owns it.
|
||||
*/
|
||||
class WakeListener(
|
||||
private val say: (WakeState) -> Unit,
|
||||
private val engine: (keywords: String) -> WakeDetector,
|
||||
private val microphone: () -> WakeMicrophone,
|
||||
private val heard: suspend (WakePhrase) -> Unit,
|
||||
private val work: CoroutineDispatcher = Dispatchers.IO,
|
||||
private val backoff: (attempt: Int) -> Long = ::wakeBackoff,
|
||||
private val log: (String, Throwable) -> Unit = { _, _ -> },
|
||||
) {
|
||||
@Volatile private var detector: WakeDetector? = null
|
||||
|
||||
@Volatile private var detectorFor: String? = null
|
||||
|
||||
/** Listen as [plans] say, until the flow ends or this is cancelled; the engine is released on the way out. */
|
||||
suspend fun follow(plans: Flow<WakePlan>) = coroutineScope {
|
||||
// Where a heard word is answered: beside the listening, so a pause does not cancel the answer.
|
||||
val answers = this
|
||||
var hearing: Job? = null
|
||||
try {
|
||||
plans.distinctUntilChanged().collect { plan ->
|
||||
hearing?.cancelAndJoin()
|
||||
hearing = null
|
||||
if (plan.pause != WakePause.None) {
|
||||
say(WakeState.Paused(plan.pause))
|
||||
} else {
|
||||
hearing = launch { hear(plan) { phrase -> answers.launch { heard(phrase) } } }
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
withContext(NonCancellable) {
|
||||
hearing?.cancelAndJoin()
|
||||
release()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun release() {
|
||||
runCatching { detector?.release() }
|
||||
detector = null
|
||||
detectorFor = null
|
||||
}
|
||||
|
||||
private val nudges = MutableStateFlow(0)
|
||||
|
||||
/** How many samples the last stretch of listening heard before it ended. */
|
||||
@Volatile private var listened = 0L
|
||||
|
||||
/** Try again now rather than when the back-off says: somebody asked. The count of failures starts over. */
|
||||
fun retryNow() = nudges.update { it + 1 }
|
||||
|
||||
/** Listen for [plan]'s phrase until cancelled: after the word, again; after a failure, again later. */
|
||||
private suspend fun hear(plan: WakePlan, heardIt: (WakePhrase) -> Unit) {
|
||||
var failures = 0
|
||||
while (true) {
|
||||
try {
|
||||
listened = 0
|
||||
listen(plan)
|
||||
failures = 0
|
||||
// Handed to the caller's scope, not run here: answering the word usually pauses
|
||||
// the listening (the sheet takes the microphone), which cancels this very loop --
|
||||
// and must not cancel the answer with it.
|
||||
heardIt(plan.phrase)
|
||||
// The sheet takes the microphone now (a new plan cancels this); otherwise listen again.
|
||||
delay(HEARD_REST_MS)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: WakeError) {
|
||||
log("wake word: ${e.why}: ${e.detail}", e)
|
||||
say(WakeState.Failed(e.why, e.detail))
|
||||
// A build without an engine does not grow one: nothing to try again.
|
||||
if (e.why == WakeFailure.NoEngine) return
|
||||
// It had been listening well for a while: this is a new trouble, not the old one again.
|
||||
if (listened >= STEADY_SAMPLES) failures = 0
|
||||
val seen = nudges.value
|
||||
val asked = withTimeoutOrNull(backoff(failures++)) { nudges.first { it != seen } } != null
|
||||
if (asked) failures = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One stretch of listening: returns when the word was heard, throws a [WakeError] when something failed. */
|
||||
private suspend fun listen(plan: WakePlan) {
|
||||
val spotter = engineFor(plan)
|
||||
try {
|
||||
withContext(work) {
|
||||
// Opened and closed on this one thread, so a cancellation cannot leave it open.
|
||||
val mic = try {
|
||||
microphone()
|
||||
} catch (e: Exception) {
|
||||
throw WakeError(WakeFailure.Microphone, e)
|
||||
}
|
||||
try {
|
||||
say(WakeState.Listening(plan.phrase.words))
|
||||
val chunk = ShortArray(CHUNK)
|
||||
var empty = 0
|
||||
var silent = 0
|
||||
while (true) {
|
||||
ensureActive()
|
||||
val read = mic.read(chunk)
|
||||
if (read < 0) throw WakeError(WakeFailure.Microphone, message = "the microphone stopped (error $read)")
|
||||
if (read == 0) {
|
||||
if (++empty > EMPTY_READS) throw WakeError(WakeFailure.Microphone, message = "the microphone gives no samples")
|
||||
continue
|
||||
}
|
||||
empty = 0
|
||||
listened += read
|
||||
val samples = FloatArray(read)
|
||||
var sound = false
|
||||
for (i in 0 until read) {
|
||||
if (chunk[i] != 0.toShort()) sound = true
|
||||
samples[i] = chunk[i] / 32768f
|
||||
}
|
||||
// Exact silence for seconds is not a quiet room: Android gives a background
|
||||
// app zeros while another app has the microphone or its switch is off.
|
||||
if (sound) {
|
||||
if (silent >= SILENT_SAMPLES) say(WakeState.Listening(plan.phrase.words))
|
||||
silent = 0
|
||||
} else if (silent < SILENT_SAMPLES) {
|
||||
silent += read
|
||||
if (silent >= SILENT_SAMPLES) say(WakeState.Paused(WakePause.Silent))
|
||||
}
|
||||
if (spotter.accept(samples)) break
|
||||
}
|
||||
} finally {
|
||||
runCatching { mic.close() }
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: WakeError) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
// The engine threw while hearing: it is not trusted again, a new one is made.
|
||||
release()
|
||||
throw WakeError(WakeFailure.Engine, e)
|
||||
}
|
||||
}
|
||||
|
||||
/** The engine for [plan]'s keywords: the one there is, or a new one once the old is released. */
|
||||
private suspend fun engineFor(plan: WakePlan): WakeDetector {
|
||||
detector?.takeIf { detectorFor == plan.keywords }?.let { return it }
|
||||
release()
|
||||
say(WakeState.Starting)
|
||||
return try {
|
||||
// Kept the moment it exists, so a cancellation while it loads cannot lose it unreleased.
|
||||
withContext(work) {
|
||||
engine(plan.keywords).also {
|
||||
detector = it
|
||||
detectorFor = plan.keywords
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: WakeError) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
// A missing native library is an Error, not an Exception: it is a failure to show all the same.
|
||||
throw WakeError(WakeFailure.Engine, e)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val RATE = 16_000
|
||||
|
||||
/** A tenth of a second at a time. */
|
||||
private const val CHUNK = RATE / 10
|
||||
private const val EMPTY_READS = 50
|
||||
private const val SILENT_SAMPLES = RATE * 5
|
||||
private const val HEARD_REST_MS = 1_500L
|
||||
|
||||
/** Half a minute of sound taken in: the microphone and the engine work. */
|
||||
private const val STEADY_SAMPLES = RATE * 30L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* What happened the last times the wake word was heard: kept (the last [WAKE_LOG_SIZE], in the
|
||||
* phone's settings) and shown in Settings › Wake word, because "it heard me and nothing opened"
|
||||
* cannot be put right without knowing which step said no. Nothing of the account is in it: the
|
||||
* phrase, clock times, and Android's own words where it refused.
|
||||
*/
|
||||
@Serializable
|
||||
data class WakeAttempt(
|
||||
/** When the phrase was heard (wall clock, ms). */
|
||||
val at: Long = 0,
|
||||
val phrase: String = "",
|
||||
/** What was tried first: a [WakeWay]'s id. */
|
||||
val way: String = "",
|
||||
/** How that went: one of the `OUT_…` words. */
|
||||
val outcome: String = "",
|
||||
/** Android's own words when it refused: the exception's class and message. */
|
||||
val detail: String = "",
|
||||
/** What was done instead, when the first way did not open the sheet: `activity`, `notification` or nothing. */
|
||||
val fallback: String = "",
|
||||
/** Whether Android said LLeMbas holds the assistant role at that moment. */
|
||||
val assistant: Boolean = false,
|
||||
/** When Android last connected the assistant service in this run of the app, and last disconnected it; 0: never. */
|
||||
val readyAt: Long = 0,
|
||||
val shutdownAt: Long = 0,
|
||||
/** Set afterwards, when the service was not connected and Android connected it later. */
|
||||
val connectedLater: Long = 0,
|
||||
/**
|
||||
* Whether Android itself said LLeMbas's service is its active voice-interaction service
|
||||
* (`VoiceInteractionService.isActiveService`). The role can be held without it: Android then
|
||||
* opens the assistant as an ordinary screen on a long press, and keeps no connection that
|
||||
* could open it from the background.
|
||||
*/
|
||||
val active: Boolean = false,
|
||||
/** Whether the phone has voice recognisers at all (`FEATURE_VOICE_RECOGNIZERS`): without it Android runs no voice-interaction service. */
|
||||
val recognizers: Boolean = true,
|
||||
val screenOn: Boolean = true,
|
||||
val locked: Boolean = false,
|
||||
/** Whether one of the app's own screens was showing. */
|
||||
val visible: Boolean = false,
|
||||
/** How long the sheet took to say it was up, in ms; -1 when none came. */
|
||||
val sheetMs: Long = -1,
|
||||
/** When the assistant service was last made and destroyed in this run of the app; 0: never. */
|
||||
val createdAt: Long = 0,
|
||||
val destroyedAt: Long = 0,
|
||||
/** Whether the wake waited for Android to connect the service (it was active but not connected yet). */
|
||||
val waited: Boolean = false,
|
||||
/** What Android told the service about this show (API 34+): it prepared one, or it failed. */
|
||||
val prepared: Boolean = false,
|
||||
val showFailed: Boolean = false,
|
||||
) {
|
||||
companion object {
|
||||
/** The sheet came up. */
|
||||
const val OUT_OPENED = "opened"
|
||||
|
||||
/** Android was asked and did not refuse, but no sheet came up in time. */
|
||||
const val OUT_NO_SHEET = "no_sheet"
|
||||
|
||||
/** The assistant service was not connected (`LembasAssistService.current` was null). */
|
||||
const val OUT_NOT_CONNECTED = "not_connected"
|
||||
|
||||
/** Android refused, with [detail]. */
|
||||
const val OUT_REFUSED = "refused"
|
||||
|
||||
/** A test in Settings took the word: nothing was to open. */
|
||||
const val OUT_TESTED = "tested"
|
||||
}
|
||||
}
|
||||
|
||||
const val WAKE_LOG_SIZE = 5
|
||||
|
||||
/** [log] with [attempt] put first, cut to the last [WAKE_LOG_SIZE]. */
|
||||
fun wakeLogAdd(log: List<WakeAttempt>, attempt: WakeAttempt): List<WakeAttempt> = (listOf(attempt) + log).take(WAKE_LOG_SIZE)
|
||||
|
||||
/**
|
||||
* Android connected the assistant service at [now]: the newest attempt that found it not
|
||||
* connected, and has not been answered yet, is told so. Anything else is left as it is.
|
||||
*/
|
||||
fun wakeLogConnected(log: List<WakeAttempt>, now: Long): List<WakeAttempt> {
|
||||
val newest = log.firstOrNull() ?: return log
|
||||
if (newest.outcome != WakeAttempt.OUT_NOT_CONNECTED || newest.connectedLater != 0L || now < newest.at) return log
|
||||
return listOf(newest.copy(connectedLater = now)) + log.drop(1)
|
||||
}
|
||||
|
||||
/** The ways the assistant may be opened when the word was heard, in the order they are worth trying. */
|
||||
enum class WakeWay(val id: String) {
|
||||
/** The assistant service is connected and the screen is on: it shows its sheet, from anywhere. */
|
||||
Session("session"),
|
||||
|
||||
/**
|
||||
* The assistant service is connected and the screen is off: a session's window turns no
|
||||
* screen on, so the sheet's activity is started through the service instead (Android lets an
|
||||
* app whose service the system has bound start one), and the activity turns the screen on.
|
||||
*/
|
||||
AssistantActivity("assistant_activity"),
|
||||
|
||||
/** No connected assistant service, but the app is on screen: the sheet's activity may start. */
|
||||
Activity("activity"),
|
||||
|
||||
/**
|
||||
* Neither: Android blocks an activity started from the background, and says nothing when it
|
||||
* does -- so it is not relied on, and a notification to tap is posted.
|
||||
*/
|
||||
Notification("notification"),
|
||||
|
||||
// A further way (answering by voice without a sheet) would be one more entry here, chosen in
|
||||
// [wakeWay] and carried out where the others are.
|
||||
}
|
||||
|
||||
/** The first way to try, from what is true at that moment. */
|
||||
fun wakeWay(connected: Boolean, screenOn: Boolean, appVisible: Boolean): WakeWay = when {
|
||||
connected && screenOn -> WakeWay.Session
|
||||
connected -> WakeWay.AssistantActivity
|
||||
appVisible -> WakeWay.Activity
|
||||
else -> WakeWay.Notification
|
||||
}
|
||||
|
||||
/**
|
||||
* The assistant service's life in this run of the app, as Android told it: when it was made,
|
||||
* connected (`onReady`), disconnected (`onShutdown`) and destroyed, what Android said of the last
|
||||
* show it was asked for, and when a sheet last came up. Written by the assistant service, the
|
||||
* session and the sheet's activity; read when the word is heard.
|
||||
*/
|
||||
object AssistLink {
|
||||
@Volatile var createdAt = 0L
|
||||
private set
|
||||
|
||||
@Volatile var destroyedAt = 0L
|
||||
private set
|
||||
|
||||
@Volatile var readyAt = 0L
|
||||
private set
|
||||
|
||||
@Volatile var shutdownAt = 0L
|
||||
private set
|
||||
|
||||
/** On the phone's elapsed clock: when Android last said it prepares to show a session, and when one failed to show. */
|
||||
@Volatile var preparedAt = 0L
|
||||
private set
|
||||
|
||||
@Volatile var showFailedAt = 0L
|
||||
private set
|
||||
|
||||
private val _shown = MutableStateFlow(0L)
|
||||
|
||||
/** When a sheet last came up, on the phone's elapsed clock (ms); 0: not yet. */
|
||||
val shown: StateFlow<Long> = _shown.asStateFlow()
|
||||
|
||||
private val _connected = MutableStateFlow(false)
|
||||
|
||||
/** Whether Android has the assistant service connected right now. */
|
||||
val connected: StateFlow<Boolean> = _connected.asStateFlow()
|
||||
|
||||
fun created(now: Long) {
|
||||
createdAt = now
|
||||
}
|
||||
|
||||
fun destroyed(now: Long) {
|
||||
destroyedAt = now
|
||||
}
|
||||
|
||||
fun ready(now: Long) {
|
||||
readyAt = now
|
||||
_connected.value = true
|
||||
}
|
||||
|
||||
fun shutdown(now: Long) {
|
||||
shutdownAt = now
|
||||
_connected.value = false
|
||||
}
|
||||
|
||||
fun prepared(elapsed: Long) {
|
||||
preparedAt = elapsed
|
||||
}
|
||||
|
||||
fun showFailed(elapsed: Long) {
|
||||
showFailedAt = elapsed
|
||||
}
|
||||
|
||||
fun sheetShown(elapsed: Long) {
|
||||
_shown.value = elapsed
|
||||
}
|
||||
}
|
||||
|
||||
/** What is true of the phone and the assistant at the moment the phrase is heard. */
|
||||
data class WakeFacts(
|
||||
/** The assistant service is connected (`LembasAssistService.current` is there). */
|
||||
val connected: Boolean,
|
||||
/** Android says the service is its active voice-interaction service. */
|
||||
val active: Boolean,
|
||||
/** LLeMbas holds the assistant role. */
|
||||
val role: Boolean,
|
||||
val recognizers: Boolean = true,
|
||||
val screenOn: Boolean = true,
|
||||
val locked: Boolean = false,
|
||||
val visible: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* Opening the assistant when the phrase was heard, apart from Android so that the order of what
|
||||
* is tried -- and what is written down about it -- can be tested.
|
||||
*
|
||||
* 1. The assistant's own way, where its service is connected ([wakeWay]). When Android says the
|
||||
* service is active but has not connected it yet, a moment is waited for the connection.
|
||||
* 2. "Opened" only once a sheet says it is up ([sheetCame]).
|
||||
* 3. Otherwise the sheet's activity -- relied on only where Android will start it: the service is
|
||||
* connected (a bound service lets the whole app start activities) or the app is on screen. A
|
||||
* session that was only slow is given a second wait first, so there are never two sheets.
|
||||
* 4. Otherwise a notification to tap.
|
||||
*
|
||||
* [open] returns what happened, for the record.
|
||||
*/
|
||||
class WakeOpener(
|
||||
private val facts: () -> WakeFacts,
|
||||
/** Wait up to the given ms for Android to connect the service; whether it did. */
|
||||
private val awaitConnected: suspend (Long) -> Boolean,
|
||||
/** Ask the connected service to show its sheet; throws what Android throws. */
|
||||
private val showSession: () -> Unit,
|
||||
/** Start the sheet's activity; throws what Android throws. */
|
||||
private val startActivity: () -> Unit,
|
||||
/** Wait up to the given ms for a sheet to say it is up; how long it took, or null. */
|
||||
private val sheetCame: suspend (Long) -> Long?,
|
||||
private val notify: (WakeAttempt) -> Unit,
|
||||
/** What Android said of the show since it was asked: prepared, failed. */
|
||||
private val showSignals: () -> Pair<Boolean, Boolean> = { false to false },
|
||||
private val now: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
suspend fun open(phrase: String, link: WakeAttempt = WakeAttempt()): WakeAttempt {
|
||||
var seen = facts()
|
||||
var waited = false
|
||||
if (!seen.connected && seen.active) {
|
||||
// Android's own assistant, only not connected at this instant: it may be on its way.
|
||||
waited = true
|
||||
if (awaitConnected(CONNECT_WAIT_MS)) seen = facts().copy(connected = true)
|
||||
}
|
||||
val way = wakeWay(seen.connected, seen.screenOn, seen.visible)
|
||||
var attempt = link.copy(
|
||||
at = now(),
|
||||
phrase = phrase,
|
||||
way = way.id,
|
||||
assistant = seen.role,
|
||||
active = seen.active,
|
||||
recognizers = seen.recognizers,
|
||||
screenOn = seen.screenOn,
|
||||
locked = seen.locked,
|
||||
visible = seen.visible,
|
||||
waited = waited,
|
||||
)
|
||||
if (way == WakeWay.Session || way == WakeWay.AssistantActivity) {
|
||||
val refused = runCatching { if (way == WakeWay.Session) showSession() else startActivity() }.exceptionOrNull()
|
||||
val took = if (refused == null) sheetCame(SHEET_WAIT_MS) else null
|
||||
val (prepared, failed) = showSignals()
|
||||
attempt = attempt.copy(prepared = prepared, showFailed = failed)
|
||||
if (took != null) return attempt.copy(outcome = WakeAttempt.OUT_OPENED, sheetMs = took)
|
||||
attempt = if (refused != null) {
|
||||
attempt.copy(outcome = WakeAttempt.OUT_REFUSED, detail = describe(refused))
|
||||
} else {
|
||||
attempt.copy(outcome = WakeAttempt.OUT_NO_SHEET)
|
||||
}
|
||||
// The activity was the way that just did not come up: starting it a second time is no fallback.
|
||||
if (way == WakeWay.AssistantActivity && refused == null) return notified(attempt)
|
||||
// A session Android did not refuse may only be slow: a second wait, before anything
|
||||
// else is put on screen beside it.
|
||||
if (refused == null) {
|
||||
sheetCame(SHEET_WAIT_MS)?.let { late -> return attempt.copy(outcome = WakeAttempt.OUT_OPENED, sheetMs = SHEET_WAIT_MS + late) }
|
||||
}
|
||||
} else {
|
||||
attempt = attempt.copy(outcome = WakeAttempt.OUT_NOT_CONNECTED)
|
||||
}
|
||||
// The sheet's activity. Android blocks one started from the background without a word,
|
||||
// so it counts only where it may start -- and only once it says it is up.
|
||||
val started = runCatching { startActivity() }.isSuccess
|
||||
if (started && (seen.connected || seen.visible)) {
|
||||
sheetCame(SHEET_WAIT_MS)?.let { took -> return attempt.copy(fallback = WakeWay.Activity.id, sheetMs = took) }
|
||||
}
|
||||
return notified(attempt)
|
||||
}
|
||||
|
||||
private fun notified(attempt: WakeAttempt): WakeAttempt {
|
||||
val told = attempt.copy(fallback = WakeWay.Notification.id)
|
||||
notify(told)
|
||||
return told
|
||||
}
|
||||
|
||||
private fun describe(e: Throwable): String = listOfNotNull(e.javaClass.simpleName, e.message?.takeIf { it.isNotBlank() }).joinToString(": ").take(200)
|
||||
|
||||
companion object {
|
||||
/** How long a sheet has to say it is up before the way that was tried counts as not having opened it. */
|
||||
const val SHEET_WAIT_MS = 2_500L
|
||||
|
||||
/** How long Android is given to connect a service it says is active. */
|
||||
const val CONNECT_WAIT_MS = 1_000L
|
||||
|
||||
/** The longest an attempt can take: the connection, three waits for a sheet, and a margin. The microphone is held that long. */
|
||||
const val ATTEMPT_MAX_MS = CONNECT_WAIT_MS + 3 * SHEET_WAIT_MS + 1_500L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioRecord
|
||||
import android.media.MediaRecorder
|
||||
import android.os.Bundle
|
||||
import android.os.PowerManager
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.ServiceCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.LifecycleService
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.assist.AssistActivity
|
||||
import eu.llembas.android.assist.LembasAssistService
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.takeWhile
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/**
|
||||
* Listening for the wake word: opt-in (Settings › Assistant › Wake word), off by default.
|
||||
*
|
||||
* A `microphone` foreground service with its notification up the whole time it runs -- Android
|
||||
* lets an app hear the microphone in the background only that way, and only once the person has
|
||||
* started it from the app. The audio goes to the on-device engine ([WakeEngine]) in memory and
|
||||
* nowhere else; it is not kept, and nothing is sent anywhere until the word is heard. Then the
|
||||
* microphone is let go and the assistant opens, listening, as the power button would open it.
|
||||
*
|
||||
* It pauses itself (the notification says why) while the assistant's sheet is up, in battery
|
||||
* saver, and -- unless Settings says otherwise -- while the screen is off; it goes on once the
|
||||
* reason is gone. It cannot start itself at boot (Android forbids a microphone service there):
|
||||
* [WakeBootReceiver] posts "tap to listen again" instead.
|
||||
*/
|
||||
class WakeWordService : LifecycleService() {
|
||||
private val screenOn = MutableStateFlow(true)
|
||||
private val batterySaver = MutableStateFlow(false)
|
||||
private val mayRecord = MutableStateFlow(true)
|
||||
private var following: Job? = null
|
||||
private var watching: Job? = null
|
||||
|
||||
/** This instance's right to write the state (WakeStatus.begin). */
|
||||
private var token = 0
|
||||
|
||||
/** The newest start Android has delivered: what the service stops itself by, so a start still on its way is not stopped. */
|
||||
private var lastStart = 0
|
||||
|
||||
/** Set when the service could not even start: the state then says why, and is not wiped on the way out. */
|
||||
private var keepState = false
|
||||
|
||||
private val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
Intent.ACTION_SCREEN_ON -> {
|
||||
screenOn.value = true
|
||||
mayRecord.value = micAllowed(this@WakeWordService)
|
||||
}
|
||||
|
||||
Intent.ACTION_SCREEN_OFF -> screenOn.value = false
|
||||
|
||||
PowerManager.ACTION_POWER_SAVE_MODE_CHANGED -> batterySaver.value = power().isPowerSaveMode
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
channel(this)
|
||||
screenOn.value = power().isInteractive
|
||||
batterySaver.value = power().isPowerSaveMode
|
||||
ContextCompat.registerReceiver(
|
||||
this,
|
||||
receiver,
|
||||
IntentFilter().apply {
|
||||
addAction(Intent.ACTION_SCREEN_ON)
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)
|
||||
},
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
super.onStartCommand(intent, flags, startId)
|
||||
// Every start counts, Stop's too: the service stops itself by the newest one it was given.
|
||||
lastStart = startId
|
||||
if (intent?.action == ACTION_STOP) {
|
||||
// Stop is the setting going off; the loop sees it and ends the service on the path
|
||||
// that has shown its notification first (follow). The service is stopped from here
|
||||
// only when nothing is running in it, and only if no newer start is on its way
|
||||
// (stopSelf(startId)): stopping under a pending foreground start closes the app.
|
||||
lifecycleScope.launch {
|
||||
lembas.instances.savePrefs { it.copy(wakeWord = false) }
|
||||
if (following?.isActive != true) stopSelf(startId)
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
mayRecord.value = micAllowed(this)
|
||||
val running = following?.isActive == true
|
||||
// The notification first: Android stops a foreground service that is slow to show one.
|
||||
// It says what is true now -- "starting" for a service that just began, and on every
|
||||
// later start (the app opens) whatever the state already is; never a phrase by default.
|
||||
val now = wakeStateAtStart(running, WakeStatus.state.value)
|
||||
try {
|
||||
ServiceCompat.startForeground(this, NOTIFICATION_ID, wakeNotification(this, now), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
|
||||
} catch (e: Exception) {
|
||||
// Android refuses a microphone service without the permission, or from the background.
|
||||
Log.w(TAG, "wake word: the service could not start", e)
|
||||
keepState = true
|
||||
WakeStatus.set(
|
||||
if (mayRecord.value) {
|
||||
WakeState.Failed(WakeFailure.Microphone, WakeError(WakeFailure.Microphone, e).detail)
|
||||
} else {
|
||||
WakeState.Paused(WakePause.NoMicrophone)
|
||||
},
|
||||
)
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
// It is listening again: "tap to listen again" (after a restart) has nothing left to say.
|
||||
manager.cancel(WakeBootReceiver.RESUME_ID)
|
||||
if (!running) {
|
||||
keepState = false
|
||||
// This instance writes the state from here; an older one's last words count for nothing.
|
||||
token = WakeStatus.begin()
|
||||
// And it starts from what the sheets say: no hold of an earlier instance is left standing.
|
||||
AssistPresence.release()
|
||||
WakeStatus.set(token, now)
|
||||
following = lifecycleScope.launch { follow() }
|
||||
}
|
||||
if (watching == null) {
|
||||
// The one place the notification is written: from the state, whenever it changes.
|
||||
watching = lifecycleScope.launch {
|
||||
WakeStatus.state.collect { state ->
|
||||
if (state != WakeState.Off) manager.notify(NOTIFICATION_ID, wakeNotification(this@WakeWordService, state))
|
||||
}
|
||||
}
|
||||
// A tap on the failure in Settings: try now, not when the back-off says.
|
||||
lifecycleScope.launch { WakeStatus.retries.drop(1).collect { listener.retryNow() } }
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private val listener by lazy {
|
||||
WakeListener(
|
||||
say = { WakeStatus.set(token, it) },
|
||||
engine = { keywords -> WakeEngine.create(this, keywords) },
|
||||
microphone = { PhoneMicrophone() },
|
||||
// A test in Settings takes the word; otherwise the assistant opens.
|
||||
heard = { phrase ->
|
||||
if (WakeStatus.heardInTrial(SystemClock.elapsedRealtime())) {
|
||||
val tested = WakeAttempt(at = System.currentTimeMillis(), phrase = phrase.words, outcome = WakeAttempt.OUT_TESTED)
|
||||
wakeScope.launch { record(this@WakeWordService, tested) }
|
||||
} else {
|
||||
wake(phrase)
|
||||
}
|
||||
},
|
||||
log = { message, cause -> Log.w(TAG, message, cause) },
|
||||
)
|
||||
}
|
||||
|
||||
/** Listen, or pause, as the phone and Settings change; stop when Settings turns it off. */
|
||||
private suspend fun follow() {
|
||||
val mine = token
|
||||
val plans = combine(lembas.instances.prefs, screenOn, batterySaver, AssistPresence.open, mayRecord) { prefs, on, saver, open, mic ->
|
||||
if (!prefs.wakeWord) {
|
||||
null
|
||||
} else {
|
||||
val phrase = WakePhrases.byId(prefs.wakePhrase)
|
||||
WakePlan(phrase, wakeKeywords(phrase, WakeSensitivity.byId(prefs.wakeSensitivity)), wakePause(on, prefs.wakeScreenOnly, saver, open > 0, mic))
|
||||
}
|
||||
}
|
||||
try {
|
||||
listener.follow(plans.takeWhile { it != null }.filterNotNull())
|
||||
} finally {
|
||||
// After the loop has ended, so nothing it said on its way out is left standing --
|
||||
// and only if no newer writer has taken over meanwhile.
|
||||
if (!keepState) WakeStatus.set(mine, WakeState.Off)
|
||||
}
|
||||
// Not if a newer start is already on its way: that one finds the loop ended and begins it again.
|
||||
stopSelf(lastStart)
|
||||
}
|
||||
|
||||
/**
|
||||
* The word was heard: the assistant opens listening ([WakeOpener] decides how and checks that
|
||||
* it did), and what was tried and how it went is written down ([WakeAttempt], kept in the
|
||||
* settings and shown in Settings › Wake word), because a silent "no" here looks to the
|
||||
* person like a wake word that does not work.
|
||||
*
|
||||
* It runs on the app's own scope, never inside the listening loop: the hold below pauses
|
||||
* the listener, which cancels the loop that heard the word -- and a wake that ran in that
|
||||
* loop was cancelled by its own first step. One at a time: a word heard while the last one
|
||||
* is still being answered is let go.
|
||||
*/
|
||||
private fun wake(phrase: WakePhrase) {
|
||||
if (waking?.isActive == true) return
|
||||
// The microphone is the sheet's from here, for as long as the attempt can take; once it
|
||||
// is over, for a moment more, and then for as long as a sheet says it is up.
|
||||
AssistPresence.holdFor(WakeOpener.ATTEMPT_MAX_MS)
|
||||
waking = wakeScope.launch {
|
||||
try {
|
||||
val asked = SystemClock.elapsedRealtime()
|
||||
val opener = WakeOpener(
|
||||
facts = { wakeFacts(this@WakeWordService) },
|
||||
awaitConnected = { ms -> withTimeoutOrNull(ms) { AssistLink.connected.first { it } } != null },
|
||||
showSession = {
|
||||
val assistant = LembasAssistService.current ?: error("the assistant service is not connected")
|
||||
assistant.showSession(Bundle().apply { putBoolean(AssistActivity.EXTRA_LISTEN, true) }, 0)
|
||||
},
|
||||
// Through the assistant service where it is connected (the same permission either way: Android lets
|
||||
// the whole app start activities while it holds the service bound).
|
||||
startActivity = { (LembasAssistService.current ?: this@WakeWordService).startActivity(AssistActivity.woken(this@WakeWordService)) },
|
||||
sheetCame = { ms ->
|
||||
withTimeoutOrNull(ms) { AssistLink.shown.first { it >= asked } }?.let { (it - asked).coerceAtLeast(0) }
|
||||
},
|
||||
notify = { attempt ->
|
||||
getSystemService(NotificationManager::class.java).notify(HEARD_ID, wakeHeardNotification(this@WakeWordService, attempt.assistant))
|
||||
},
|
||||
showSignals = { (AssistLink.preparedAt >= asked) to (AssistLink.showFailedAt >= asked) },
|
||||
)
|
||||
val link = WakeAttempt(
|
||||
createdAt = AssistLink.createdAt,
|
||||
destroyedAt = AssistLink.destroyedAt,
|
||||
readyAt = AssistLink.readyAt,
|
||||
shutdownAt = AssistLink.shutdownAt,
|
||||
)
|
||||
record(this@WakeWordService, opener.open(phrase.words, link))
|
||||
} finally {
|
||||
AssistPresence.holdFor(SHEET_GRACE_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var waking: Job? = null
|
||||
|
||||
private fun power() = getSystemService(PowerManager::class.java)
|
||||
|
||||
override fun onDestroy() {
|
||||
runCatching { unregisterReceiver(receiver) }
|
||||
// The scope ends with the service: the listener's loop is joined and its engine released
|
||||
// on the way out (WakeListener.follow), not here under a loop that may still run.
|
||||
if (!keepState) WakeStatus.set(token, WakeState.Off)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val CHANNEL = "wake_word"
|
||||
const val CHANNEL_HEARD = "wake_heard"
|
||||
private const val NOTIFICATION_ID = 7001
|
||||
const val HEARD_ID = 7002
|
||||
private const val SHEET_GRACE_MS = 3_000L
|
||||
|
||||
/** `PackageManager.FEATURE_VOICE_RECOGNIZERS`, which the SDK does not name for apps: without it Android runs no voice-interaction service. */
|
||||
private const val FEATURE_VOICE_RECOGNIZERS = "android.software.voice_recognizers"
|
||||
|
||||
/** The app's own scope: a wake and its record outlive the listening loop, and the service too. */
|
||||
private val wakeScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
|
||||
/** What is true at this moment, for the opener and the record. */
|
||||
fun wakeFacts(context: Context): WakeFacts = WakeFacts(
|
||||
connected = LembasAssistService.current != null,
|
||||
active = LembasAssistService.isActive(context),
|
||||
role = LembasAssistService.holdsRole(context),
|
||||
recognizers = context.packageManager.hasSystemFeature(FEATURE_VOICE_RECOGNIZERS),
|
||||
screenOn = context.getSystemService(PowerManager::class.java).isInteractive,
|
||||
locked = context.getSystemService(KeyguardManager::class.java).isKeyguardLocked,
|
||||
visible = AppVisibility.visible,
|
||||
)
|
||||
|
||||
/**
|
||||
* Write [attempt] down: in the log under a fixed tag, and first among the last few in the
|
||||
* settings. Not cancellable: what happened is kept whatever ends meanwhile.
|
||||
*/
|
||||
suspend fun record(context: Context, attempt: WakeAttempt) = withContext(NonCancellable) {
|
||||
Log.i(TAG, "wake word heard: $attempt")
|
||||
runCatching { context.lembas.instances.savePrefs { it.copy(wakeLog = wakeLogAdd(it.wakeLog, attempt)) } }
|
||||
Unit
|
||||
}
|
||||
private const val TAG = "LLeMbasWake"
|
||||
const val ACTION_STOP = "eu.llembas.android.action.WAKE_STOP"
|
||||
|
||||
/**
|
||||
* Start listening, or say why not. Only from the app on screen: Android allows a
|
||||
* microphone service from there, and only with the microphone permission -- without it
|
||||
* the service is not started at all, and the state says so.
|
||||
*/
|
||||
fun start(context: Context) {
|
||||
if (!WakeEngine.AVAILABLE) return WakeStatus.set(WakeState.Failed(WakeFailure.NoEngine))
|
||||
if (!micAllowed(context)) return WakeStatus.set(WakeState.Paused(WakePause.NoMicrophone))
|
||||
try {
|
||||
ContextCompat.startForegroundService(context, Intent(context, WakeWordService::class.java))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "wake word: the service could not be started", e)
|
||||
WakeStatus.set(WakeState.Failed(WakeFailure.Microphone, WakeError(WakeFailure.Microphone, e).detail))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The wake word was turned off. The service is not stopped from outside: it ends itself
|
||||
* when it sees the setting, after it has shown its notification -- stopping it under a
|
||||
* foreground start that is still on its way closes the app. The state is "off" at once.
|
||||
*/
|
||||
fun stop() {
|
||||
WakeStatus.set(WakeState.Off)
|
||||
}
|
||||
|
||||
fun micAllowed(context: Context) = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
fun channel(context: Context) {
|
||||
context.getSystemService(NotificationManager::class.java).createNotificationChannels(
|
||||
listOf(
|
||||
NotificationChannel(CHANNEL, context.getString(R.string.channel_wake), NotificationManager.IMPORTANCE_LOW),
|
||||
// "Heard you. Tap to ask.": it must come up over what is on screen, or the word was for nothing.
|
||||
NotificationChannel(CHANNEL_HEARD, context.getString(R.string.channel_wake_heard), NotificationManager.IMPORTANCE_HIGH),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "Heard you. Tap to ask.": what the wake word posts when it cannot open the assistant itself.
|
||||
* A fixed sentence, nothing from the account; the tap opens the assistant listening.
|
||||
*/
|
||||
fun wakeHeardNotification(context: Context, assistant: Boolean = false): Notification {
|
||||
val ask = PendingIntent.getActivity(context, 1, AssistActivity.listening(context), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
return NotificationCompat.Builder(context, WakeWordService.CHANNEL_HEARD)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.wake_heard))
|
||||
// Why it is a notification and not the sheet, in fixed words: LLeMbas is not the phone's
|
||||
// assistant -- or it is, and could not open by itself this time (Settings says which step said no).
|
||||
.setContentText(context.getString(if (assistant) R.string.wake_heard_could_not else R.string.wake_heard_line))
|
||||
.setContentIntent(ask)
|
||||
.setAutoCancel(true)
|
||||
.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.setTimeoutAfter(HEARD_TIMEOUT_MS)
|
||||
.build()
|
||||
}
|
||||
|
||||
/** A minute: a "tap to ask" nobody tapped is no longer an answer to anything. */
|
||||
private const val HEARD_TIMEOUT_MS = 60_000L
|
||||
|
||||
/**
|
||||
* The persistent notification, from [state] alone: what the wake word is doing in plain words
|
||||
* (the phrase it listens for, why it is paused, what failed). Nothing from the account.
|
||||
*/
|
||||
fun wakeNotification(context: Context, state: WakeState): Notification {
|
||||
val stop = PendingIntent.getService(
|
||||
context,
|
||||
2,
|
||||
Intent(context, WakeWordService::class.java).setAction(WakeWordService.ACTION_STOP),
|
||||
PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val open = PendingIntent.getActivity(context, 3, Intent(context, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
|
||||
return NotificationCompat.Builder(context, WakeWordService.CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(wakeTitle(context, state))
|
||||
.setContentText(wakeLine(context, state))
|
||||
.setOngoing(true)
|
||||
.setSilent(true)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.setContentIntent(open)
|
||||
.addAction(0, context.getString(R.string.wake_stop), stop)
|
||||
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone's microphone at 16 kHz, recording from the moment it is made -- or an exception that
|
||||
* says what did not work. Android reports none of this by throwing: a recorder that could not be
|
||||
* opened is merely "uninitialized", and one that did not start merely "stopped".
|
||||
*/
|
||||
@android.annotation.SuppressLint("MissingPermission")
|
||||
private class PhoneMicrophone : WakeMicrophone {
|
||||
private val audio: AudioRecord
|
||||
|
||||
init {
|
||||
val rate = WakeListener.RATE
|
||||
val min = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
|
||||
check(min > 0) { "the phone cannot record at 16 kHz" }
|
||||
audio = AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, maxOf(min, rate))
|
||||
try {
|
||||
check(audio.state == AudioRecord.STATE_INITIALIZED) { "the microphone could not be opened" }
|
||||
audio.startRecording()
|
||||
check(audio.recordingState == AudioRecord.RECORDSTATE_RECORDING) { "recording did not start; another app may have the microphone" }
|
||||
} catch (e: Exception) {
|
||||
audio.release()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
override fun read(into: ShortArray): Int = audio.read(into, 0, into.size)
|
||||
|
||||
override fun close() {
|
||||
runCatching { audio.stop() }
|
||||
audio.release()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* After a restart: Android does not let a microphone service start at boot, so a wake word that
|
||||
* was on says "tap to listen again" -- the tap opens the app, which starts it.
|
||||
*/
|
||||
class WakeBootReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action != Intent.ACTION_BOOT_COMPLETED && intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) return
|
||||
val pending = goAsync()
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
try {
|
||||
val prefs = context.lembas.instances.prefs.first()
|
||||
if (!prefs.wakeWord || !WakeEngine.AVAILABLE) return@launch
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return@launch
|
||||
WakeWordService.channel(context)
|
||||
val open = PendingIntent.getActivity(
|
||||
context,
|
||||
4,
|
||||
Intent(context, MainActivity::class.java).putExtra(EXTRA_RESUME, true).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
context.getSystemService(NotificationManager::class.java).notify(
|
||||
RESUME_ID,
|
||||
NotificationCompat.Builder(context, WakeWordService.CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.wake_resume))
|
||||
.setContentText(context.getString(R.string.wake_resume_line))
|
||||
.setContentIntent(open)
|
||||
.setAutoCancel(true)
|
||||
.build(),
|
||||
)
|
||||
} finally {
|
||||
pending.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** On MainActivity's intent: start listening for the wake word again. */
|
||||
const val EXTRA_RESUME = "eu.llembas.android.WAKE_RESUME"
|
||||
const val RESUME_ID = 7003
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Generated by scripts/gen-wake-phrases.py from the model's bpe.model. Do not edit: edit the lists there.
|
||||
package eu.llembas.android.wake
|
||||
|
||||
/**
|
||||
* The words a wake phrase is made of -- a greeting and a name -- each with its spelling in the
|
||||
* model's BPE pieces (`sherpa-onnx-kws-zipformer-gigaspeech-3.3M-2024-01-01`). English, as the
|
||||
* model is.
|
||||
*
|
||||
* Left out, because the tokenizer can only spell them out letter by letter:
|
||||
* Elizabeth (▁E LI Z A B E TH)
|
||||
* Benjamin (▁BE N J A M IN)
|
||||
*/
|
||||
object WakeWords {
|
||||
val greetings = listOf(
|
||||
WakeWord("hey", "Hey", "▁HE Y"),
|
||||
WakeWord("ok", "OK", "▁OKAY"),
|
||||
WakeWord("hello", "Hello", "▁HE LL O"),
|
||||
)
|
||||
|
||||
val names = listOf(
|
||||
WakeWord("assistant", "Assistant", "▁AS S IST ANT"),
|
||||
WakeWord("computer", "Computer", "▁COMP U TER"),
|
||||
WakeWord("google", "Google", "▁GO O G LE"),
|
||||
WakeWord("victoria", "Victoria", "▁VI C T OR IA"),
|
||||
WakeWord("samantha", "Samantha", "▁SA MAN TH A"),
|
||||
WakeWord("jessica", "Jessica", "▁JE S S IC A"),
|
||||
WakeWord("amanda", "Amanda", "▁A MAN D A"),
|
||||
WakeWord("olivia", "Olivia", "▁O LI VI A"),
|
||||
WakeWord("oliver", "Oliver", "▁O LI VER"),
|
||||
WakeWord("sebastian", "Sebastian", "▁SE B AS T IAN"),
|
||||
WakeWord("jonathan", "Jonathan", "▁JO N A TH AN"),
|
||||
WakeWord("alexander", "Alexander", "▁A LE X AN DER"),
|
||||
WakeWord("christopher", "Christopher", "▁ CH R IST O PH ER"),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package eu.llembas.android.widget
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProvider
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ShortcutInfo
|
||||
import android.content.pm.ShortcutManager
|
||||
import android.graphics.drawable.Icon
|
||||
import android.widget.RemoteViews
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.assist.AssistActivity
|
||||
|
||||
/**
|
||||
* The home-screen widget: a bar that opens the assistant's sheet (Ask), the sheet listening (the
|
||||
* microphone), or the sheet at the last chat the assistant made. Nothing on it comes from the
|
||||
* account, so it never needs updating and shows nothing private wherever it is placed.
|
||||
*/
|
||||
class AskWidget : AppWidgetProvider() {
|
||||
override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {
|
||||
val views = RemoteViews(context.packageName, R.layout.widget_ask).apply {
|
||||
setOnClickPendingIntent(R.id.widget_ask, open(context, REQUEST_ASK, Intent(context, AssistActivity::class.java).setAction(Intent.ACTION_ASSIST)))
|
||||
setOnClickPendingIntent(R.id.widget_mic, open(context, REQUEST_LISTEN, AssistActivity.listening(context)))
|
||||
setOnClickPendingIntent(R.id.widget_last, open(context, REQUEST_CONTINUE, AssistActivity.continuing(context)))
|
||||
}
|
||||
ids.forEach { manager.updateAppWidget(it, views) }
|
||||
}
|
||||
|
||||
private fun open(context: Context, request: Int, intent: Intent): PendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
request,
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
companion object {
|
||||
private const val REQUEST_ASK = 1
|
||||
private const val REQUEST_LISTEN = 2
|
||||
private const val REQUEST_CONTINUE = 3
|
||||
|
||||
/**
|
||||
* Give every placed widget its buttons again. Nothing on it changes -- but the intents
|
||||
* behind the buttons carry the app's own mark ([eu.llembas.android.assist.OwnIntents]),
|
||||
* and a widget placed by an older version has buttons without it.
|
||||
*/
|
||||
fun refresh(context: Context) {
|
||||
val manager = AppWidgetManager.getInstance(context) ?: return
|
||||
val ids = runCatching { manager.getAppWidgetIds(ComponentName(context, AskWidget::class.java)) }.getOrNull() ?: return
|
||||
if (ids.isNotEmpty()) AskWidget().onUpdate(context, manager, ids)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The launcher icon's long-press shortcuts: Ask, Speak and the last assistant chat. Published from
|
||||
* code rather than `shortcuts.xml`, because a static shortcut names the package, and the test
|
||||
* build's is `….debug`; and so their labels follow the app's language.
|
||||
*/
|
||||
object Shortcuts {
|
||||
fun publish(context: Context) {
|
||||
val manager = context.getSystemService(ShortcutManager::class.java) ?: return
|
||||
val shortcuts = listOf(
|
||||
shortcut(
|
||||
context,
|
||||
"ask",
|
||||
R.string.tile_ask,
|
||||
R.string.tile_ask,
|
||||
R.drawable.ic_shortcut_ask,
|
||||
Intent(context, AssistActivity::class.java).setAction(Intent.ACTION_ASSIST),
|
||||
),
|
||||
shortcut(context, "speak", R.string.widget_speak, R.string.widget_speak, R.drawable.ic_shortcut_mic, AssistActivity.listening(context)),
|
||||
shortcut(context, "continue", R.string.shortcut_last, R.string.assist_continue, R.drawable.ic_shortcut_history, AssistActivity.continuing(context)),
|
||||
)
|
||||
runCatching { manager.dynamicShortcuts = shortcuts }
|
||||
}
|
||||
|
||||
private fun shortcut(context: Context, id: String, short: Int, long: Int, icon: Int, intent: Intent): ShortcutInfo = ShortcutInfo.Builder(context, id)
|
||||
.setShortLabel(context.getString(short))
|
||||
.setLongLabel(context.getString(long))
|
||||
.setIcon(Icon.createWithResource(context, icon))
|
||||
.setIntent(intent)
|
||||
.build()
|
||||
}
|
||||
@@ -3,11 +3,12 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp" android:height="108dp"
|
||||
android:viewportWidth="108" android:viewportHeight="108">
|
||||
<group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">
|
||||
<path android:fillColor="#0B0D10" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M15,1h1v1h-1z M6,2h2v1h-2z M15,2h1v1h-1z M5,3h1v1h-1z M15,3h1v1h-1z M5,4h1v1h-1z M14,4h1v1h-1z M4,5h1v1h-1z M14,5h1v1h-1z M4,6h1v1h-1z M14,6h1v1h-1z M3,7h1v1h-1z M13,7h1v1h-1z M3,8h1v1h-1z M12,8h1v1h-1z M3,9h1v1h-1z M11,9h1v1h-1z M3,10h1v1h-1z M10,10h1v1h-1z M3,11h1v1h-1z M7,11h3v1h-3z M2,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
|
||||
<path android:fillColor="#4FAE5A" android:pathData="M14,2h1v1h-1z M13,3h2v1h-2z M12,4h2v1h-2z M11,5h3v1h-3z M10,6h4v1h-4z M9,7h4v1h-4z M8,8h4v1h-4z M7,9h4v1h-4z M6,10h4v1h-4z M5,11h2v1h-2z M3,12h1v1h-1z M2,13h1v1h-1z M1,14h1v1h-1z"/>
|
||||
<path android:fillColor="#7EE081" android:pathData="M11,1h4v1h-4z M10,2h2v1h-2z M9,3h2v1h-2z M8,4h2v1h-2z M7,5h2v1h-2z M6,6h2v1h-2z M5,7h2v1h-2z M4,8h2v1h-2z M4,9h1v1h-1z M4,11h1v1h-1z"/>
|
||||
<path android:fillColor="#B6F2A6" android:pathData="M10,1h1v1h-1z M8,2h2v1h-2z M6,3h3v1h-3z M6,4h2v1h-2z M5,5h2v1h-2z M5,6h1v1h-1z M4,7h1v1h-1z"/>
|
||||
<path android:fillColor="#D8FFD0" android:pathData="M12,2h2v1h-2z M11,3h2v1h-2z M10,4h2v1h-2z M9,5h2v1h-2z M8,6h2v1h-2z M7,7h2v1h-2z M6,8h2v1h-2z M5,9h2v1h-2z M4,10h2v1h-2z"/>
|
||||
<group android:translateX="21" android:translateY="21" android:scaleX="2.75" android:scaleY="2.75">
|
||||
<path android:fillColor="#0B0D10" android:pathData="M12,2h5v1h-5z M10,3h2v1h-2z M17,3h1v1h-1z M8,4h2v1h-2z M17,4h1v1h-1z M7,5h1v1h-1z M17,5h1v1h-1z M7,6h1v1h-1z M16,6h1v1h-1z M6,7h1v1h-1z M16,7h1v1h-1z M6,8h1v1h-1z M16,8h1v1h-1z M5,9h1v1h-1z M15,9h1v1h-1z M5,10h1v1h-1z M14,10h1v1h-1z M5,11h1v1h-1z M13,11h1v1h-1z M5,12h1v1h-1z M12,12h1v1h-1z M5,13h1v1h-1z M9,13h3v1h-3z M4,14h1v1h-1z M6,14h3v1h-3z M3,15h1v1h-1z M5,15h1v1h-1z M2,16h1v1h-1z M4,16h1v1h-1z M3,17h1v1h-1z"/>
|
||||
<path android:fillColor="#4FAE5A" android:pathData="M16,4h1v1h-1z M15,5h2v1h-2z M14,6h2v1h-2z M13,7h3v1h-3z M12,8h4v1h-4z M11,9h4v1h-4z M10,10h4v1h-4z M9,11h4v1h-4z M8,12h4v1h-4z M7,13h2v1h-2z M5,14h1v1h-1z M4,15h1v1h-1z M3,16h1v1h-1z"/>
|
||||
<path android:fillColor="#7EE081" android:pathData="M13,3h4v1h-4z M12,4h2v1h-2z M11,5h2v1h-2z M10,6h2v1h-2z M9,7h2v1h-2z M8,8h2v1h-2z M7,9h2v1h-2z M6,10h2v1h-2z M6,11h1v1h-1z M6,13h1v1h-1z"/>
|
||||
<path android:fillColor="#B6F2A6" android:pathData="M12,3h1v1h-1z M10,4h2v1h-2z M8,5h3v1h-3z M8,6h2v1h-2z M7,7h2v1h-2z M7,8h1v1h-1z M6,9h1v1h-1z"/>
|
||||
<path android:fillColor="#C792EA" android:pathData="M15,14h5v1h-5z M15,15h1v1h-1z M19,15h1v1h-1z M15,16h1v1h-1z M19,16h1v1h-1z M15,17h1v1h-1z M19,17h1v1h-1z M15,18h1v1h-1z M19,18h1v1h-1z M15,19h1v1h-1z M17,19h1v1h-1z M19,19h1v1h-1z M15,20h5v1h-5z"/>
|
||||
<path android:fillColor="#D8FFD0" android:pathData="M14,4h2v1h-2z M13,5h2v1h-2z M12,6h2v1h-2z M11,7h2v1h-2z M10,8h2v1h-2z M9,9h2v1h-2z M8,10h2v1h-2z M7,11h2v1h-2z M6,12h2v1h-2z"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -3,7 +3,7 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp" android:height="108dp"
|
||||
android:viewportWidth="108" android:viewportHeight="108">
|
||||
<group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M10,1h1v1h-1z M11,1h4v1h-4z M15,1h1v1h-1z M6,2h2v1h-2z M8,2h2v1h-2z M10,2h2v1h-2z M12,2h2v1h-2z M14,2h1v1h-1z M15,2h1v1h-1z M5,3h1v1h-1z M6,3h3v1h-3z M9,3h2v1h-2z M11,3h2v1h-2z M13,3h2v1h-2z M15,3h1v1h-1z M5,4h1v1h-1z M6,4h2v1h-2z M8,4h2v1h-2z M10,4h2v1h-2z M12,4h2v1h-2z M14,4h1v1h-1z M4,5h1v1h-1z M5,5h2v1h-2z M7,5h2v1h-2z M9,5h2v1h-2z M11,5h3v1h-3z M14,5h1v1h-1z M4,6h1v1h-1z M5,6h1v1h-1z M6,6h2v1h-2z M8,6h2v1h-2z M10,6h4v1h-4z M14,6h1v1h-1z M3,7h1v1h-1z M4,7h1v1h-1z M5,7h2v1h-2z M7,7h2v1h-2z M9,7h4v1h-4z M13,7h1v1h-1z M3,8h1v1h-1z M4,8h2v1h-2z M6,8h2v1h-2z M8,8h4v1h-4z M12,8h1v1h-1z M3,9h1v1h-1z M4,9h1v1h-1z M5,9h2v1h-2z M7,9h4v1h-4z M11,9h1v1h-1z M3,10h1v1h-1z M4,10h2v1h-2z M6,10h4v1h-4z M10,10h1v1h-1z M3,11h1v1h-1z M4,11h1v1h-1z M5,11h2v1h-2z M7,11h3v1h-3z M2,12h1v1h-1z M3,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M2,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M1,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
|
||||
<group android:translateX="21" android:translateY="21" android:scaleX="2.75" android:scaleY="2.75">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M12,2h5v1h-5z M10,3h2v1h-2z M12,3h1v1h-1z M13,3h4v1h-4z M17,3h1v1h-1z M8,4h2v1h-2z M10,4h2v1h-2z M12,4h2v1h-2z M14,4h2v1h-2z M16,4h1v1h-1z M17,4h1v1h-1z M7,5h1v1h-1z M8,5h3v1h-3z M11,5h2v1h-2z M13,5h2v1h-2z M15,5h2v1h-2z M17,5h1v1h-1z M7,6h1v1h-1z M8,6h2v1h-2z M10,6h2v1h-2z M12,6h2v1h-2z M14,6h2v1h-2z M16,6h1v1h-1z M6,7h1v1h-1z M7,7h2v1h-2z M9,7h2v1h-2z M11,7h2v1h-2z M13,7h3v1h-3z M16,7h1v1h-1z M6,8h1v1h-1z M7,8h1v1h-1z M8,8h2v1h-2z M10,8h2v1h-2z M12,8h4v1h-4z M16,8h1v1h-1z M5,9h1v1h-1z M6,9h1v1h-1z M7,9h2v1h-2z M9,9h2v1h-2z M11,9h4v1h-4z M15,9h1v1h-1z M5,10h1v1h-1z M6,10h2v1h-2z M8,10h2v1h-2z M10,10h4v1h-4z M14,10h1v1h-1z M5,11h1v1h-1z M6,11h1v1h-1z M7,11h2v1h-2z M9,11h4v1h-4z M13,11h1v1h-1z M5,12h1v1h-1z M6,12h2v1h-2z M8,12h4v1h-4z M12,12h1v1h-1z M5,13h1v1h-1z M6,13h1v1h-1z M7,13h2v1h-2z M9,13h3v1h-3z M4,14h1v1h-1z M5,14h1v1h-1z M6,14h3v1h-3z M3,15h1v1h-1z M4,15h1v1h-1z M5,15h1v1h-1z M2,16h1v1h-1z M3,16h1v1h-1z M4,16h1v1h-1z M3,17h1v1h-1z M15,14h5v1h-5z M15,15h1v1h-1z M19,15h1v1h-1z M15,16h1v1h-1z M19,16h1v1h-1z M15,17h1v1h-1z M19,17h1v1h-1z M15,18h1v1h-1z M19,18h1v1h-1z M15,19h1v1h-1z M17,19h1v1h-1z M19,19h1v1h-1z M15,20h5v1h-5z"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A launcher shortcut's icon: a Material icon (Apache-2.0) on a disc, in the theme's colours. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="48dp" android:height="48dp"
|
||||
android:viewportWidth="48" android:viewportHeight="48">
|
||||
<path android:fillColor="@color/token_surface_raised" android:pathData="M24,0a24,24 0,1 1,0 48a24,24 0,1 1,0 -48z" />
|
||||
<group android:translateX="12" android:translateY="12">
|
||||
<path android:fillColor="@color/token_accent" android:pathData="M20,2L4,2c-1.1,0 -1.99,0.9 -1.99,2L2,22l4,-4h14c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2z" />
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A launcher shortcut's icon: a Material icon (Apache-2.0) on a disc, in the theme's colours. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="48dp" android:height="48dp"
|
||||
android:viewportWidth="48" android:viewportHeight="48">
|
||||
<path android:fillColor="@color/token_surface_raised" android:pathData="M24,0a24,24 0,1 1,0 48a24,24 0,1 1,0 -48z" />
|
||||
<group android:translateX="12" android:translateY="12">
|
||||
<path android:fillColor="@color/token_accent" android:pathData="M13,3c-4.97,0 -9,4.03 -9,9L1,12l3.89,3.89 0.07,0.14L9,12L6,12c0,-3.87 3.13,-7 7,-7s7,3.13 7,7 -3.13,7 -7,7c-1.93,0 -3.68,-0.79 -4.94,-2.06l-1.42,1.42C8.27,19.99 10.51,21 13,21c4.97,0 9,-4.03 9,-9s-4.03,-9 -9,-9zM12,8v5l4.28,2.54 0.72,-1.21 -3.5,-2.08L13.5,8L12,8z" />
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A launcher shortcut's icon: a Material icon (Apache-2.0) on a disc, in the theme's colours. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="48dp" android:height="48dp"
|
||||
android:viewportWidth="48" android:viewportHeight="48">
|
||||
<path android:fillColor="@color/token_surface_raised" android:pathData="M24,0a24,24 0,1 1,0 48a24,24 0,1 1,0 -48z" />
|
||||
<group android:translateX="12" android:translateY="12">
|
||||
<path android:fillColor="@color/token_accent" android:pathData="M12,14c1.66,0 2.99,-1.34 2.99,-3L15,5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v6c0,1.66 1.34,3 3,3zM17.3,11c0,3 -2.54,5.1 -5.3,5.1S6.7,14 6.7,11L5,11c0,3.41 2.72,6.23 6,6.72L11,21h2v-3.28c3.28,-0.48 6,-3.3 6,-6.72h-1.7z" />
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A Material icon (Apache-2.0) in the theme's colour (values*/tokens.xml). -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp" android:height="24dp"
|
||||
android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="@color/token_accent" android:pathData="M20,2L4,2c-1.1,0 -1.99,0.9 -1.99,2L2,22l4,-4h14c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A Material icon (Apache-2.0) in the theme's colour (values*/tokens.xml). -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp" android:height="24dp"
|
||||
android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="@color/token_ink_muted" android:pathData="M13,3c-4.97,0 -9,4.03 -9,9L1,12l3.89,3.89 0.07,0.14L9,12L6,12c0,-3.87 3.13,-7 7,-7s7,3.13 7,7 -3.13,7 -7,7c-1.93,0 -3.68,-0.79 -4.94,-2.06l-1.42,1.42C8.27,19.99 10.51,21 13,21c4.97,0 9,-4.03 9,-9s-4.03,-9 -9,-9zM12,8v5l4.28,2.54 0.72,-1.21 -3.5,-2.08L13.5,8L12,8z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A Material icon (Apache-2.0) in the theme's colour (values*/tokens.xml). -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp" android:height="24dp"
|
||||
android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="@color/token_accent_ink" android:pathData="M12,14c1.66,0 2.99,-1.34 2.99,-3L15,5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v6c0,1.66 1.34,3 3,3zM17.3,11c0,3 -2.54,5.1 -5.3,5.1S6.7,14 6.7,11L5,11c0,3.41 2.72,6.23 6,6.72L11,21h2v-3.28c3.28,-0.48 6,-3.3 6,-6.72h-1.7z" />
|
||||
</vector>
|
||||
Loaded 100 of 271 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user