Compare commits

..
Author SHA1 Message Date
HomerandClaude Opus 5.5 2d38ccd321 LLeMbas for Android 1.0.0-beta.7: pinned to LLeMbas 2.0.0-beta.10
CI / check (push) Canceled after 0s
Release / release (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:47:11 +00:00
HomerandClaude Opus 5.5 f816919071 Phone actions: the confirm card and the capability (harness spec 3.6.0, server e463621)
CI / check (push) Canceled after 0s
- Contract and strings pinned at server dev e463621 (event_ask_phone.json); tokens unchanged.
- Every message declares client ["phone_actions"] (POST /chats and /chats/{id}/messages).
- CardItem.phone; a phone_action card (chat card sheet, and inline in the assistant's sheet):
  the model's summary, how it will be done, its facts, the map app to use when Settings leaves
  it open, Google Maps' limits said; Cancel answers declined, Do it runs ActionRunner and
  answers {result: {status, message}} -- done or failed with why. Locked: "unlock first".
- Executor on the spec's fields: alarm time HH:MM/days/label, timer, calendar_event
  (start/end local, notes), sms_draft (numbers only; names left to the person), email_draft
  with cc, dial, open_app by name, open_url, media command, torch on, settings_panel,
  automation_intent (Tasker's ACTION_TASK by name with values as local variables, else
  LLeMbas's own AUTOMATION broadcast), navigate (replace_route -> OsmAnd force), add_stop,
  search_nearby (near), stop_navigation. Tool-result reasons in English, for the model.
- Tests: PhoneActionsTest reads the fixture; shots 35-38 phone cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:51:32 +00:00
HomerandClaude Opus 5.5 9906554d09 Phone actions, groundwork: the executor and its settings, before the server's phone_action
CI / check (push) Canceled after 0s
- actions/PhoneActions: standard intents for alarm, timer, calendar insert, SMS and email
  drafts, dial (the dialler, never a call), open URL (http/https only), open app (package or
  launcher label), settings panels, automation broadcasts (never android.* / com.android.*);
  torch via CameraManager; media keys via AudioManager.
- actions/Navigation: Google Maps (google.navigation:, the dir URL with waypoints, geo:0,0?q=;
  no adding to a running route, no stop) and OsmAnd through its intent API only
  (osmand.api:// navigate, navigate_gpx with route points as GPX data, navigate_search,
  stop_navigation; no OsmAnd code, which is GPLv3). add_stop re-plans here -> stop -> destination.
- Optional OsmAnd get_info (Settings switch, after allowing LLeMbas inside OsmAnd): position and
  the running route's destination, through a see-through ResultActivity.
- Settings › Navigation app: whichever is installed (both: ask), Google Maps, OsmAnd, ask.
- Not wired yet: the confirm card and the capability wait for the server's spec 3.6.0 fixtures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:39:11 +00:00
HomerandClaude Opus 5.5 9ca27cee01 Notification summaries on request: NotificationListenerService, off by default
CI / check (push) Canceled after 0s
- LembasNotificationListener keeps nothing; NotificationReader.read takes the notifications up
  now (not ours, not ongoing, not group summaries; newest 40, 600 chars each, 12k in all) and
  returns nothing while the phone is locked.
- The assistant sends them with one question: its "Summarise my notifications" chip, or a
  question naming them (assist_notifications_phrases, per language).
- Settings › Assistant › Notification summaries: the app's switch (off) and, when on, Android's
  notification-access page with whether it is given; a privacy paragraph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:29:14 +00:00
HomerandClaude Opus 5.5 dc642c62b9 Opt-in wake word: on-device keyword spotting in a microphone foreground service
CI / check (push) Canceled after 0s
- Engine: sherpa-onnx 2.0.1 keyword spotter (Apache-2.0) with the English
  zipformer-gigaspeech-3.3M KWS model (Apache-2.0, int8), fetched hash-pinned by
  scripts/fetch-wakeword.py into app/libs and src/full/assets (gitignored); CI and release run it.
  `full` flavour only (abiFilters arm64-v8a, armeabi-v7a, x86_64); `fdroid` has a stub engine
  and Settings says why. ProGuard keeps com.k2fsa.sherpa.onnx (JNI reads fields by name).
- WakeWordService (foregroundServiceType microphone): persistent notification with Stop; audio
  only to the engine in memory; pauses while the sheet is up (AssistPresence), in battery saver,
  and with the screen off unless Settings says otherwise. On the word: the sheet opens listening
  through LembasAssistService.showSession when LLeMbas is the assistant, else the activity,
  else a "tap to ask" notification.
- No microphone service at boot: WakeBootReceiver posts "tap to listen again"; MainActivity
  restarts a service the phone stopped.
- Settings › Assistant › Wake word: switch (off), four built-in English phrases (BPE-tokenized
  with the model's bpe.model), screen-on only, battery-optimisation page; privacy and cost text.
- The sheet's "no wake word" line now points at the setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:27:51 +00:00
HomerandClaude Opus 5.5 2080f0b67e Share sheet: the last chat is known to the Send row too
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:19:33 +00:00
HomerandClaude Opus 5.5 9592fbeeb4 Syntax highlighting in the file viewer and in a reply's code blocks
CI / check (push) Canceled after 0s
A small scanner of the app's own (ui/Highlight.kt) rather than Prism4j (annotation processor,
unmaintained since 2019): comments, strings, numbers, keywords, types, markup tags/attributes,
YAML/TOML keys and shell/PHP variables for the server's `show` languages plus common fence
aliases. Colours are theme tokens only (accent, success, warning, leaf, ink-faint). The viewer
highlights off the main thread (plain until ready; at once in previews); over 400k chars stays
plain. HighlightTest; shots 33-viewer-{kotlin,python,yaml,typescript}, 34-code-block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:17:39 +00:00
HomerandClaude Opus 5.5 9976186599 Spoken conversation mode: listen again after each spoken answer until stopped
CI / check (push) Canceled after 0s
- A spoken question answered aloud opens a conversation (Settings › Assistant, on by default,
  needs voice replies); after the answer is heard to the end, the sheet listens again.
- Ends on a stop phrase (assist_stop_words, per language; isStopPhrase), End, typing, a stopped
  voice, a card waiting, or nothing said (the existing silence timeout).
- "In conversation" banner with End in the sheet's foot; shot 24-assistant-conversation.
- HeadsetRoute: a Bluetooth headset made the communication device (Android 12+) and its
  microphone preferred by the recorder, so the conversation can stay in the ear.
- Speaker.playToEnd tells a voice heard to the end from one stopped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:16:15 +00:00
HomerandClaude Opus 5.5 d46e7aa548 Widget layout: no double hyphen inside an XML comment (aapt refuses it)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:16:15 +00:00
HomerandClaude Opus 5.5 77e1539e8f Assistant entry points: share sheet (new or last chat), widget, shortcuts, headset button
CI / check (push) Canceled after 0s
- Share: a sheet over the sharing app shows what came in, takes an optional request, and sends
  to a new chat or the last assistant chat; files uploaded first; a new chat becomes the last.
- Home-screen widget (RemoteViews, nothing from the account): Ask, Speak, last chat.
- Launcher shortcuts published from code (the debug build's package differs): Ask, Speak, Last.
- ACTION_VOICE_COMMAND / VOICE_SEARCH_HANDS_FREE open the sheet listening; locked: unlock first.
- Quick Settings tile: STATE_INACTIVE (never greyed out), TOGGLEABLE_TILE false.
- fetch-tokens.py also writes values{,-night}/tokens.xml for what Compose cannot draw.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:05:11 +00:00
71 changed files with 5250 additions and 194 deletions

No files matched your search

+4
View File
@@ -37,6 +37,10 @@ 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
- uses: gradle/actions/wrapper-validation@v4
- uses: gradle/actions/setup-gradle@v4
+4
View File
@@ -43,6 +43,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
+3
View File
@@ -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/
+52
View File
@@ -3,6 +3,58 @@
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.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).
+7 -1
View File
@@ -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.7"
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
@@ -82,6 +82,8 @@ android {
create("full") {
dimension = "distribution"
buildConfigField("boolean", "SELF_UPDATE", "true")
// The wake-word engine's native code: phones and the 64-bit emulator, not 32-bit x86.
ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a", "x86_64") }
}
create("fdroid") {
dimension = "distribution"
@@ -156,6 +158,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)
+3
View File
@@ -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, phrase: WakePhrase): WakeDetector? = null
}
@@ -0,0 +1,75 @@
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 once, into the app's no-backup files, 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")
fun create(context: Context, phrase: WakePhrase): WakeDetector? = runCatching {
val dir = File(context.noBackupFilesDir, "wakeword").apply { mkdirs() }
for (name in FILES) {
val target = File(dir, name)
val size = context.assets.openFd("wakeword/$name").use { it.length }
if (!target.exists() || (size >= 0 && target.length() != size)) {
context.assets.open("wakeword/$name").use { input -> target.outputStream().use { input.copyTo(it) } }
}
}
val keywords = File(dir, "keywords.txt").apply { writeText("${phrase.tokens} @${phrase.id}\n") }
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 = keywords.path,
)
SherpaDetector(KeywordSpotter(null, config))
}.getOrNull()
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()
}
}
}
+83 -4
View File
@@ -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,11 +59,11 @@
<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). -->
<activity
android:name=".assist.AssistActivity"
android:exported="true"
@@ -55,6 +76,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 +92,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 +110,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 +163,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,6 +178,32 @@
</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" />
<!-- Notification summaries (opt-in): read only when a question asks for them. -->
<service
android:name=".notify.LembasNotificationListener"
android:exported="true"
android:label="@string/notification_summaries"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
<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" />
@@ -27,6 +27,8 @@ class LembasApp : Application() {
// LLeMbas 2.0 has no reports, so 0.1's channel for them goes rather than sit empty in
// the system's settings.
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)
}
companion object {
@@ -54,6 +54,9 @@ 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
@@ -75,6 +78,10 @@ class MainActivity : ComponentActivity() {
super.onCreate(savedInstanceState)
take(intent)
followLanguage()
// A wake word that is on, but whose service the phone stopped: it listens again.
lifecycleScope.launch {
if (WakeEngine.AVAILABLE && lembas.instances.prefs.first().wakeWord) runCatching { WakeWordService.start(this@MainActivity) }
}
// At most once a day, and only while Settings › About says so (update/ReleaseCheck.kt).
lifecycleScope.launch { runCatching { ReleaseCheck(this@MainActivity).daily() } }
if (Build.VERSION.SDK_INT >= 33 &&
@@ -115,6 +122,11 @@ class MainActivity : ComponentActivity() {
}
private fun take(intent: Intent?) {
// "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) }
}
val chat = intent?.getStringExtra(Notifications.EXTRA_CHAT)
val schedule = intent?.getStringExtra(Notifications.EXTRA_SCHEDULE)
val run = intent?.getStringExtra(Notifications.EXTRA_RUN)
@@ -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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"))
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
}
}
@@ -239,6 +239,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 +259,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)
},
)
@@ -513,6 +515,12 @@ 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 message (spec 3.6.0): the phone carries out
* `phone_action` calls the person confirms here, so the chat is offered the tool.
*/
private val CAPABILITIES = JsonArray(listOf(JsonPrimitive("phone_actions")))
/** 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
@@ -544,6 +544,11 @@ data class CardItem(
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,
)
@Serializable
@@ -582,6 +587,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,6 +596,9 @@ 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)
@@ -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)
@@ -3,6 +3,7 @@ package eu.llembas.android.assist
import android.Manifest
import android.app.KeyguardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
@@ -16,6 +17,34 @@ 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.AssistPresence
/** 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.
*/
fun of(intent: Intent): Opening = when {
intent.getBooleanExtra(AssistActivity.EXTRA_LISTEN, false) -> Listen
intent.action == AssistActivity.ACTION_CONTINUE -> Continue
intent.action in LISTENING -> Listen
else -> Sheet
}
private val LISTENING = setOf(
AssistActivity.ACTION_LISTEN,
Intent.ACTION_VOICE_COMMAND,
"android.speech.action.VOICE_SEARCH_HANDS_FREE",
)
}
}
/**
* The assistant as an activity: what the Quick Settings tile, the "Ask" shortcut and a plain
@@ -27,6 +56,7 @@ import eu.llembas.android.ui.theme.LembasTheme
*/
class AssistActivity : ComponentActivity() {
private lateinit var controller: AssistController
private lateinit var keyguard: KeyguardManager
/** Whether the phone is locked: the sheet shows nothing from the account until it is not. */
private val locked = mutableStateOf(false)
@@ -41,31 +71,10 @@ 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)
} else {
controller.opened(locked = false)
}
AssistPresence.shown()
take(intent)
setContent {
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
LembasTheme(prefs.theme) {
@@ -94,7 +103,52 @@ class AssistActivity : ComponentActivity() {
}
}
/** Opened again while it is up -- the headset's button pressed twice, the tile again. */
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
take(intent)
}
/**
* What the way in asked for: a question handed over by the session, listening (the headset's
* voice button, the widget's microphone, the Speak shortcut), the last assistant chat (the
* widget, the shortcut), or just the sheet. Over the lock screen each waits for Android to
* unlock first.
*/
private fun take(intent: Intent) {
val opening = Opening.of(intent)
val waiting = intent.getStringExtra(EXTRA_QUESTION).orEmpty()
val go = {
when {
waiting.isNotBlank() -> controller.ask(waiting)
opening == Opening.Continue -> controller.continueWhenReady()
opening == Opening.Listen && !controller.micAllowed() -> mic.launch(Manifest.permission.RECORD_AUDIO)
opening == Opening.Listen -> controller.opened(locked = false, listen = true)
else -> controller.opened(locked = false)
}
}
if (keyguard.isKeyguardLocked) {
keyguard.requestDismissKeyguard(
this,
object : KeyguardManager.KeyguardDismissCallback() {
override fun onDismissSucceeded() {
locked.value = false
go()
}
override fun onDismissCancelled() = finish()
override fun onDismissError() = finish()
},
)
} else {
go()
}
}
override fun onDestroy() {
AssistPresence.hidden()
controller.close()
super.onDestroy()
}
@@ -104,5 +158,17 @@ class AssistActivity : ComponentActivity() {
/** 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 = Intent(context, AssistActivity::class.java).setAction(ACTION_LISTEN)
/** The sheet, at the last assistant chat. */
fun continuing(context: Context): Intent = Intent(context, AssistActivity::class.java).setAction(ACTION_CONTINUE)
}
}
@@ -10,11 +10,14 @@ import androidx.core.content.ContextCompat
import eu.llembas.android.MainActivity
import eu.llembas.android.R
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.ModelInfo
import eu.llembas.android.api.Step
import eu.llembas.android.api.StreamClient
import eu.llembas.android.lembas
import eu.llembas.android.notify.NotificationReader
import eu.llembas.android.push.Notifications
import eu.llembas.android.ui.explain
import kotlinx.coroutines.CoroutineScope
@@ -71,6 +74,13 @@ 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,
) {
val screenAvailable: Boolean get() = screenText || screenshot != null
val modelInfo: ModelInfo? get() = models.firstOrNull { it.id == modelId }
@@ -94,6 +104,9 @@ interface AssistActions {
fun voiceReply(on: Boolean) {}
fun readAloud() {}
fun stopReading() {}
fun endConversation() {}
fun summariseNotifications() {}
fun answerCard(card: Card, answer: CardAnswer) {}
}
/**
@@ -116,6 +129,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
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
private var usingPhone = false
@@ -138,6 +152,7 @@ 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 && NotificationReader.granted(context),
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
)
@@ -168,14 +183,25 @@ 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).
* screen), or the microphone is not allowed yet (that needs an activity to ask). [listen]
* is a way in that means to speak -- a headset's voice button -- and listens regardless.
*/
fun opened(locked: Boolean) {
fun opened(locked: Boolean, listen: Boolean = false) {
scope.launch {
ready.join()
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 && !locked && (listen || prefs.assistantListens) && s.canListen && !s.listening && micAllowed()) {
if (listen || s.empty) listen()
}
}
}
/** Open at the last assistant chat, once it is known which that is. */
fun continueWhenReady() {
scope.launch {
ready.join()
if (_state.value.last != null) continueLast() else opened(locked = false)
}
}
@@ -204,13 +230,15 @@ 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) } },
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 +246,14 @@ 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),
)
}
},
)
} else {
recorder.preferred = headset
recorder.start()
launch { recorder.level.collect { l -> _state.update { it.copy(level = l) } } }
launch { writeDownAsSaid() }
@@ -306,20 +336,33 @@ class AssistController(private val context: Context, private val scope: Coroutin
_state.update { it.copy(busy = true) }
val text = context.lembas.instances.client()?.transcribe(wav).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) {
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,13 +374,20 @@ 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)
fun ask(question: String, spoken: Boolean, notifications: Boolean = false) {
if (question.isBlank()) return
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.")
@@ -347,7 +397,19 @@ class AssistController(private val context: Context, private val scope: Coroutin
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 (NotificationReader.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(NotificationReader.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
@@ -373,9 +435,16 @@ class AssistController(private val context: Context, private val scope: Coroutin
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()))
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()) 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) }
}
@@ -408,10 +477,25 @@ 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) }
_state.update { it.copy(chatId = null, turns = emptyList(), error = null, busy = false, conversation = false) }
}
/** The model: for the chat this sheet is in, changed at once; for a new one, kept for next time. */
@@ -438,15 +522,18 @@ 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))
/** Read [words] aloud; true when they were heard to the end. */
private suspend fun speak(words: String): Boolean {
if (words.isBlank()) return false
return try {
val api = context.lembas.instances.client() ?: return false
speaker.playToEnd(api.speech(words))
} catch (e: Exception) {
_state.update { it.copy(error = context.explain(e)) }
false
}
}
@@ -461,6 +548,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
hearing?.cancel()
speaker.stop()
phone.stop()
route.release()
scope.launch { recorder.stop() }
}
@@ -473,6 +561,7 @@ 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,
@@ -27,6 +27,7 @@ import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import eu.llembas.android.AppLanguage
import eu.llembas.android.lembas
import eu.llembas.android.ui.theme.LembasTheme
import eu.llembas.android.wake.AssistPresence
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
@@ -41,7 +42,28 @@ 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 onReady() {
super.onReady()
current = this
}
override fun onShutdown() {
if (current === this) current = null
super.onShutdown()
}
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
}
}
class LembasAssistSessionService : VoiceInteractionSessionService() {
override fun onNewSession(args: Bundle?): VoiceInteractionSession = LembasAssistSession(this)
@@ -109,7 +131,9 @@ class LembasAssistSession(context: Context) :
override fun onShow(args: Bundle?, showFlags: Int) {
super.onShow(args, showFlags)
registry.currentState = Lifecycle.State.RESUMED
controller.opened(locked())
AssistPresence.shown()
// The wake word asks for the sheet listening, whatever Settings says about opening.
controller.opened(locked(), listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true)
}
/**
@@ -119,6 +143,7 @@ class LembasAssistSession(context: Context) :
*/
override fun onHide() {
super.onHide()
AssistPresence.hidden()
controller.close()
scope.cancel()
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
@@ -42,10 +42,12 @@ 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.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
@@ -89,6 +91,7 @@ import androidx.compose.ui.unit.dp
import eu.llembas.android.R
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.progressLineOf
import eu.llembas.android.ui.theme.LocalPalette
@@ -276,6 +279,7 @@ fun ColumnScope.AssistSheetContent(
// 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)
@@ -441,9 +445,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)
}
}
@@ -474,6 +482,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 +511,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) {
@@ -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))
@@ -143,11 +150,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 +170,7 @@ class Speaker(private val context: Context) {
file.delete()
player = null
_playing.value = false
done.complete(true)
}
prepare()
start()
@@ -166,6 +178,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 +191,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.
@@ -85,6 +85,20 @@ 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. */
val wakePhrase: String = "hey_lembas",
/** 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,102 @@
package eu.llembas.android.notify
import android.app.KeyguardManager
import android.app.Notification
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import androidx.core.app.NotificationManagerCompat
/**
* Notification summaries on request: the assistant reads the notifications on the phone only when
* the person asks it to ("summarise my notifications", or the sheet's chip), and sends their text
* with that one question. Off by default, twice over: Android's own notification-access switch
* (which only the person can turn on, in the system's settings) and Settings › Assistant's.
*
* The listener keeps nothing: it is how Android lets an app read the notifications that are up
* right now ([activeNotifications]), and nothing is read until a question asks for it. Never over
* the lock screen ([read] returns nothing while the phone is locked).
*/
class LembasNotificationListener : NotificationListenerService() {
override fun onListenerConnected() {
super.onListenerConnected()
current = this
}
override fun onListenerDisconnected() {
if (current === this) current = null
super.onListenerDisconnected()
}
companion object {
@Volatile
var current: LembasNotificationListener? = null
private set
}
}
/** One notification, as the question carries it. */
data class Notice(val app: String, val title: String, val text: String, val at: Long)
object NotificationReader {
/** Whether the person gave LLeMbas notification access in the system's settings. */
fun granted(context: Context): Boolean = context.packageName in NotificationManagerCompat.getEnabledListenerPackages(context)
/** The system's page for this app's notification access (the detail page where Android has one). */
fun settingsIntent(context: Context): Intent = if (Build.VERSION.SDK_INT >= 30) {
Intent(Settings.ACTION_NOTIFICATION_LISTENER_DETAIL_SETTINGS)
.putExtra(Settings.EXTRA_NOTIFICATION_LISTENER_COMPONENT_NAME, ComponentName(context, LembasNotificationListener::class.java).flattenToString())
} else {
Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
/** The notifications up now, newest first -- or none, when locked or not allowed. */
fun read(context: Context): List<Notice> {
if (context.getSystemService(KeyguardManager::class.java).isKeyguardLocked) return emptyList()
val listener = LembasNotificationListener.current ?: return emptyList()
val shown = runCatching { listener.activeNotifications }.getOrNull().orEmpty()
return shown
.filter { it.packageName != context.packageName && !it.isOngoing && it.notification.flags and Notification.FLAG_GROUP_SUMMARY == 0 }
.sortedByDescending { it.postTime }
.mapNotNull { notice(context, it) }
.take(MAX_NOTICES)
}
private fun notice(context: Context, sbn: StatusBarNotification): Notice? {
val extras = sbn.notification.extras
val title = extras.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
val lines = extras.getCharSequenceArray(Notification.EXTRA_TEXT_LINES)?.joinToString("\n").orEmpty()
val text = (extras.getCharSequence(Notification.EXTRA_BIG_TEXT) ?: extras.getCharSequence(Notification.EXTRA_TEXT))?.toString()
?.ifBlank { null } ?: lines
if (title.isBlank() && text.isBlank()) return null
val app = runCatching {
val pm = context.packageManager
pm.getApplicationLabel(pm.getApplicationInfo(sbn.packageName, 0)).toString()
}.getOrDefault(sbn.packageName)
return Notice(app, title, text.take(MAX_TEXT), sbn.postTime)
}
/** 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_NOTICES = 40
private const val MAX_TEXT = 600
private const val MAX_CHARS = 12_000
}
@@ -7,108 +7,131 @@ import android.os.Bundle
import android.provider.OpenableColumns
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.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
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.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.ui.explain
import eu.llembas.android.ui.theme.LembasTheme
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.
*/
class ShareActivity : ComponentActivity() {
private val failure = mutableStateOf<String?>(null)
class ShareActivity :
ComponentActivity(),
ShareActions {
private val state = MutableStateFlow(ShareState())
private var uris: List<Uri> = emptyList()
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
uris = 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()
}
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, files = uris.map { uri -> SharedFile(nameOf(uri), (contentResolver.getType(uri) ?: "").startsWith("image/")) }) }
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()
LembasTheme(prefs.theme) {
AssistSheetFrame(onDismiss = ::cancel) { handle, _ -> ShareSheetContent(shown, this@ShareActivity, handle) }
}
}
}
override fun cancel() = finish()
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
val files = uris.map { uri ->
val bytes = withContext(Dispatchers.IO) { contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0) }
api.upload(nameOf(uri), contentResolver.getType(uri) ?: "application/octet-stream", bytes, into).id
}
val message = shareMessage(ask, now.text, getString(R.string.share_default_prompt))
val chatId = if (into != null) {
api.sendMessage(into, message, files)
into
} else {
val prefs = store.prefs.first()
val made = api.createChat(message, files, model = prefs.assistantModel.ifBlank { null })
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: 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 = explain(e)) }
}
}
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))
Intent.ACTION_SEND_MULTIPLE ->
IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java).orEmpty()
else -> emptyList()
}
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))
}
api.upload(name, contentResolver.getType(uri) ?: "application/octet-stream", bytes).id
}
if (text.isBlank() && files.isEmpty()) {
finish()
return
}
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)
}
}
private fun nameOf(uri: Uri): String = runCatching {
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
}.getOrNull() ?: uri.lastPathSegment ?: "shared"
}
@@ -0,0 +1,230 @@
package eu.llembas.android.share
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.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.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. */
data class SharedFile(val name: String, val image: Boolean)
/** 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,
)
/** 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) {}
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, or the
* last chat the assistant made -- and Send. Rows of unknown height stack; the two 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) }
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))
}
}
// 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,
enabled = !state.sending,
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
)
// Where it goes.
if (last != null) {
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, enabled = !state.sending) { toLast = false }
Destination(Icons.Filled.History, stringResource(R.string.assist_continue), last.title, selected = toLast, enabled = !state.sending) {
toLast =
true
}
}
}
}
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 = { actions.send(ask, toLast && last != null) },
enabled = !state.sending && (state.text.isNotBlank() || state.files.isNotEmpty()),
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
modifier = Modifier.heightIn(min = 48.dp),
) { Text(stringResource(if (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()}"
}
@@ -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)
@@ -58,6 +58,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)
}
@@ -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",
)
@@ -88,6 +88,7 @@ import eu.llembas.android.api.ToolCall
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.progressLineOf
import eu.llembas.android.ui.splitFences
import eu.llembas.android.ui.theme.LocalPalette
@@ -391,8 +392,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,
@@ -2,9 +2,13 @@
package eu.llembas.android.ui.settings
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
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,17 +30,24 @@ 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.Forum
import androidx.compose.material.icons.filled.Hearing
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.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
@@ -71,13 +82,16 @@ 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.assist.PhoneRecognizer
import eu.llembas.android.auth.Instance
import eu.llembas.android.auth.Prefs
import eu.llembas.android.lembas
import eu.llembas.android.notify.NotificationReader
import eu.llembas.android.push.Push
import eu.llembas.android.ui.theme.LocalPalette
import eu.llembas.android.update.AppVersion
@@ -87,6 +101,9 @@ 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.WakeEngine
import eu.llembas.android.wake.WakePhrases
import eu.llembas.android.wake.WakeWordService
import kotlinx.coroutines.launch
/** What the settings page does; every action has a do-nothing default for the screenshots. */
@@ -102,6 +119,15 @@ interface SettingsActions {
fun assistantTemporary(on: Boolean) {}
fun voiceInput(value: String) {}
fun assistantListens(on: Boolean) {}
fun assistantConversation(on: Boolean) {}
fun wakeWord(on: Boolean) {}
fun wakePhrase(id: String) {}
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() {}
@@ -126,6 +152,12 @@ 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,
/** Whether Android's notification access is given to LLeMbas. */
val notificationAccess: Boolean = false,
/** The navigation apps installed: NavApp ids. */
val navApps: List<String> = emptyList(),
)
@Composable
@@ -141,6 +173,15 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
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) {
@@ -196,6 +237,58 @@ 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(context)
}
}
}
override fun wakePhrase(id: String) {
scope.launch { store.savePrefs { it.copy(wakePhrase = id) } }
}
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 && !NotificationReader.granted(context)) notificationAccess()
}
override fun notificationAccess() {
runCatching { context.startActivity(NotificationReader.settingsIntent(context)) }
}
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 +343,10 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
selfUpdate = BuildConfig.SELF_UPDATE,
beta = beta,
phoneRecognizer = remember { PhoneRecognizer.available(context) },
wakeAvailable = WakeEngine.AVAILABLE,
// Read again each time Settings is composed: the person comes back from the system's page.
notificationAccess = NotificationReader.granted(context),
navApps = remember { NavApp.installedApps(context).map { it.id } },
),
actions,
onBack,
@@ -408,14 +505,32 @@ 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),
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,
)
},
)
}
Text(
stringResource(R.string.assistant_samsung) + "\n\n" + stringResource(R.string.assist_no_wake_word),
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) }
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,6 +612,138 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
}
}
/**
* The wake word: off until turned on; the phrase (the engine's own, English); 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 WakeWordGroup(state: SettingsState, actions: SettingsActions) {
val palette = LocalPalette.current
val on = state.prefs.wakeWord && state.wakeAvailable
Group(stringResource(R.string.wake_word)) {
SettingRow(
Icons.Filled.Hearing,
stringResource(R.string.wake_word_listen),
subtitle = stringResource(if (state.wakeAvailable) R.string.wake_word_line else R.string.wake_word_unavailable),
enabled = state.wakeAvailable,
onClick = { actions.wakeWord(!on) },
trailing = { Switch(checked = on, enabled = state.wakeAvailable, onCheckedChange = actions::wakeWord) },
)
if (state.wakeAvailable) {
WakePhrases.all.forEach { phrase ->
Rule()
SettingRow(
Icons.Filled.RecordVoiceOver,
"“${phrase.words}”",
showIcon = false,
onClick = { actions.wakePhrase(phrase.id) },
trailing = { RadioButton(selected = state.prefs.wakePhrase == phrase.id, onClick = { actions.wakePhrase(phrase.id) }) },
)
}
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(
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. */
@Composable
private fun NotificationSummaryGroup(state: SettingsState, actions: SettingsActions) {
val palette = LocalPalette.current
val on = state.prefs.notificationSummaries
Group(stringResource(R.string.notification_summaries)) {
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,
)
}
}
Text(
stringResource(R.string.notification_summaries_privacy),
style = MaterialTheme.typography.bodySmall,
color = palette.inkFaint,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
}
@Composable
private fun Group(title: String, content: @Composable () -> Unit) {
val palette = LocalPalette.current
@@ -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.10. Do not edit.
package eu.llembas.android.ui.theme
import androidx.compose.ui.graphics.Color
@@ -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)) },
@@ -120,7 +127,7 @@ fun TreeFileViewer(path: String, onClose: () -> Unit) {
val file = api.fileContent(path)
val withheld = file.withheld
when {
withheld == null -> Loaded.Text(file.text, file.viewKind)
withheld == null -> Loaded.Text(file.text, file.viewKind, file.language)
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))
@@ -217,15 +224,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 +259,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 +270,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,12 +300,27 @@ 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))
}
}
}
}
/** [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
}
}
private fun copy(context: Context, label: String, text: String) {
context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText(label, text))
}
@@ -0,0 +1,71 @@
package eu.llembas.android.wake
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
/**
* A wake word the engine ships: what the person says ([words]), the engine's spelling of it
* ([tokens], the model's BPE pieces, worked out once with its `bpe.model` -- the phone has no
* tokenizer), and the id Settings keeps.
*
* Only phrases from this list can be chosen: an open-vocabulary spotter hears any phrase it can
* spell, but how well each one works was not measured, 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 id: String, val words: String, val tokens: String)
object WakePhrases {
val all = listOf(
WakePhrase("hey_lembas", "Hey Lembas", "▁HE Y ▁LE M B AS"),
WakePhrase("ok_lembas", "OK Lembas", "▁O K ▁LE M B AS"),
WakePhrase("hello_lembas", "Hello Lembas", "▁HE LL O ▁LE M B AS"),
WakePhrase("hey_assistant", "Hey Assistant", "▁HE Y ▁AS S IST ANT"),
)
val default: WakePhrase get() = all.first()
fun byId(id: String): WakePhrase = all.firstOrNull { it.id == id } ?: default
}
/**
* 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()
}
/**
* 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.
*/
object AssistPresence {
private val _open = MutableStateFlow(0)
val open: StateFlow<Int> = _open.asStateFlow()
fun shown() = _open.update { it + 1 }
fun hidden() = _open.update { (it - 1).coerceAtLeast(0) }
}
/** Why listening for the wake word is paused, or [None]: what the notification and Settings say. */
enum class WakePause { None, ScreenOff, BatterySaver, Assistant, NoMicrophone }
/**
* 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
}
@@ -0,0 +1,300 @@
package eu.llembas.android.wake
import android.Manifest
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 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.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* 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 var listening: Job? = null
private var detector: WakeDetector? = null
private var phraseId: String? = null
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_SCREEN_ON -> screenOn.value = true
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)
if (intent?.action == ACTION_STOP) {
lifecycleScope.launch {
lembas.instances.savePrefs { it.copy(wakeWord = false) }
stopSelf()
}
return START_NOT_STICKY
}
// The notification first: Android stops a foreground service that is slow to show one.
ServiceCompat.startForeground(this, NOTIFICATION_ID, notification(null, WakePause.None), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
if (listening == null) follow()
return START_NOT_STICKY
}
/** Listen, or pause, as the phone and Settings change; stop when Settings turns it off. */
private fun follow() {
listening = lifecycleScope.launch {
combine(lembas.instances.prefs, screenOn, batterySaver, AssistPresence.open) { prefs, on, saver, open ->
if (!prefs.wakeWord) {
null
} else {
prefs.wakePhrase to wakePause(on, prefs.wakeScreenOnly, saver, open > 0, micAllowed())
}
}.distinctUntilChanged().collect { now ->
if (now == null) {
stopSelf()
return@collect
}
val (id, pause) = now
val phrase = WakePhrases.byId(id)
notify(phrase, pause)
hearing?.cancel()
hearing = if (pause == WakePause.None) launch { hear(phrase) } else null
}
}
}
private var hearing: Job? = null
@android.annotation.SuppressLint("MissingPermission")
private suspend fun hear(phrase: WakePhrase) {
val engine = withContext(Dispatchers.Default) {
if (phraseId != phrase.id) {
detector?.release()
detector = WakeEngine.create(this@WakeWordService, phrase)
phraseId = phrase.id
}
detector
} ?: return notify(phrase, WakePause.NoMicrophone)
val min = AudioRecord.getMinBufferSize(RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
val audio = runCatching {
AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, maxOf(min, RATE))
}.getOrNull() ?: return
var heard = false
withContext(Dispatchers.IO) {
try {
audio.startRecording()
val chunk = ShortArray(RATE / 10)
val samples = FloatArray(chunk.size)
while (isActive && !heard) {
val read = audio.read(chunk, 0, chunk.size)
if (read <= 0) continue
for (i in 0 until read) samples[i] = chunk[i] / 32768f
heard = engine.accept(if (read == chunk.size) samples else samples.copyOf(read))
}
} finally {
runCatching { audio.stop() }
audio.release()
}
}
if (heard) wake()
}
/**
* The word was heard: the assistant opens listening. Through the voice-interaction service
* when LLeMbas is the phone's assistant (Android lets it open the sheet from the background),
* else as an activity; and if Android refuses that too, a notification to tap.
*/
private fun wake() {
AssistPresence.shown() // the microphone is the sheet's from here, until it says it is gone
val shownBySystem = LembasAssistService.current?.let { service ->
runCatching { service.showSession(Bundle().apply { putBoolean(AssistActivity.EXTRA_LISTEN, true) }, 0) }.isSuccess
} ?: false
val opened = shownBySystem || runCatching { startActivity(AssistActivity.listening(this).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }.isSuccess
if (!opened) {
getSystemService(NotificationManager::class.java).notify(
HEARD_ID,
NotificationCompat.Builder(this, CHANNEL)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.wake_heard))
.setContentIntent(PendingIntent.getActivity(this, 1, AssistActivity.listening(this), PendingIntent.FLAG_IMMUTABLE))
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build(),
)
}
// Released by the sheet as it shows and hides; if nothing opened, at once.
lifecycleScope.launch {
delay(SHEET_GRACE_MS)
AssistPresence.hidden()
}
}
private fun notify(phrase: WakePhrase, pause: WakePause) {
getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification(phrase, pause))
}
/** What the persistent notification says: the phrase it listens for, or why it is paused. Nothing from the account. */
private fun notification(phrase: WakePhrase?, pause: WakePause): Notification {
val title = when (pause) {
WakePause.None -> getString(R.string.wake_listening_for, (phrase ?: WakePhrases.default).words)
WakePause.ScreenOff -> getString(R.string.wake_paused_screen)
WakePause.BatterySaver -> getString(R.string.wake_paused_battery)
WakePause.Assistant -> getString(R.string.wake_paused_assistant)
WakePause.NoMicrophone -> getString(R.string.wake_paused_microphone)
}
val stop = PendingIntent.getService(this, 2, Intent(this, WakeWordService::class.java).setAction(ACTION_STOP), PendingIntent.FLAG_IMMUTABLE)
val open = PendingIntent.getActivity(this, 3, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
return NotificationCompat.Builder(this, CHANNEL)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(getString(R.string.wake_notification_line))
.setOngoing(true)
.setSilent(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(open)
.addAction(0, getString(R.string.wake_stop), stop)
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
.build()
}
private fun micAllowed() = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
private fun power() = getSystemService(PowerManager::class.java)
override fun onDestroy() {
hearing?.cancel()
listening?.cancel()
runCatching { unregisterReceiver(receiver) }
detector?.release()
detector = null
super.onDestroy()
}
companion object {
const val CHANNEL = "wake_word"
private const val NOTIFICATION_ID = 7001
private const val HEARD_ID = 7002
private const val RATE = 16_000
private const val SHEET_GRACE_MS = 3_000L
const val ACTION_STOP = "eu.llembas.android.action.WAKE_STOP"
/** Start listening. Only from the app on screen: Android allows a microphone service from there. */
fun start(context: Context) {
ContextCompat.startForegroundService(context, Intent(context, WakeWordService::class.java))
}
fun stop(context: Context) {
context.stopService(Intent(context, WakeWordService::class.java))
}
fun channel(context: Context) {
context.getSystemService(NotificationManager::class.java).createNotificationChannel(
NotificationChannel(CHANNEL, context.getString(R.string.channel_wake), NotificationManager.IMPORTANCE_LOW),
)
}
}
}
/**
* 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,73 @@
package eu.llembas.android.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
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,
)
private companion object {
const val REQUEST_ASK = 1
const val REQUEST_LISTEN = 2
const val REQUEST_CONTINUE = 3
}
}
/**
* 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()
}
@@ -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>
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The widget's bar, in the theme's colours (values*/tokens.xml). -->
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/token_surface" />
<stroke android:width="1dp" android:color="@color/token_border" />
<corners android:radius="28dp" />
</shape>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="@color/token_accent" />
</shape>
+59
View File
@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The home-screen widget: Ask (the sheet), the microphone (the sheet, listening) and the last
assistant chat. It shows nothing from the account (no chat title, no model), so nothing
of it is private wherever the launcher shows it. Every part keeps a fixed size except the
Ask label, which gives. -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/widget_background"
android:gravity="center_vertical"
android:minHeight="56dp"
android:orientation="horizontal"
android:paddingStart="16dp"
android:paddingEnd="4dp">
<LinearLayout
android:id="@+id/widget_ask"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_weight="1"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:importantForAccessibility="no"
android:src="@drawable/ic_widget_ask" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:ellipsize="end"
android:maxLines="1"
android:text="@string/widget_hint"
android:textColor="@color/token_ink_muted"
android:textSize="16sp" />
</LinearLayout>
<ImageView
android:id="@+id/widget_last"
android:layout_width="48dp"
android:layout_height="48dp"
android:contentDescription="@string/assist_continue"
android:padding="12dp"
android:src="@drawable/ic_widget_history" />
<ImageView
android:id="@+id/widget_mic"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginStart="2dp"
android:background="@drawable/widget_mic_background"
android:contentDescription="@string/widget_speak"
android:padding="12dp"
android:src="@drawable/ic_widget_mic" />
</LinearLayout>
+69 -1
View File
@@ -377,7 +377,6 @@
<string name="assist_quick_explain_prompt">Vysvětli, co je na mé obrazovce.</string>
<string name="assist_continue">Pokračovat v poslední konverzaci</string>
<string name="assist_help">Podržením tlačítka napájení otevřete asistenta nad libovolnou aplikací; nebo použijte dlaždici v Rychlém nastavení.</string>
<string name="assist_no_wake_word">Budicí slovo není: na běžném Androidu je naslouchání budicímu slovu vyhrazeno asistentovi zabudovanému v telefonu.</string>
<string name="assist_connecting">Připojování…</string>
<string name="assist_offline">%1$s není dostupná</string>
<string name="assist_no_model">Žádný model</string>
@@ -390,6 +389,70 @@
<string name="assist_say_it">Řekněte to a odmlčte se</string>
<string name="assist_type">Raději psát</string>
<string name="assist_writing_down">Zapisuji, co jste řekli…</string>
<string name="assist_conversation">Rozhovor</string>
<string name="assist_conversation_line">Po každé odpovědi znovu poslouchám. Řekněte „stop“ a skončíme.</string>
<string name="assist_conversation_end">Ukončit</string>
<string name="assist_stop_words">stop|dost|to je vše|to je všechno|konec|nashledanou|díky to je vše|zrušit|stop stop</string>
<string name="assistant_conversation">Pokračovat v mluveném rozhovoru</string>
<string name="assistant_conversation_line">Po přečtení mluvené odpovědi asistent znovu poslouchá — dokud neřeknete „stop“, neklepnete na Ukončit nebo pár sekund nic neřeknete. Funguje i se sluchátky.</string>
<string name="assist_wake_word_hint">Budicí slovo jen pokud chcete: Nastavení › Asistent › Budicí slovo zapne vlastní slovo LLeMbas, přímo v tomto telefonu.</string>
<string name="channel_wake">Budicí slovo</string>
<string name="wake_word">Budicí slovo</string>
<string name="wake_word_listen">Naslouchat budicímu slovu</string>
<string name="wake_word_line">Ve výchozím stavu vypnuto. Řekněte frázi a asistent se otevře a poslouchá, nad jakoukoli aplikací na obrazovce.</string>
<string name="wake_word_unavailable">V tomto sestavení není. Sestavení pro F-Droid nemá modul pro budicí slovo, protože F-Droid sestavuje každou knihovnu ze zdrojů; sestavení z llembas.eu ho má.</string>
<string name="wake_screen_only">Jen při zapnuté obrazovce</string>
<string name="wake_screen_only_line">Vypnuto: poslouchá i při zhasnuté obrazovce, za cenu vyšší spotřeby baterie.</string>
<string name="wake_battery">Nechat běžet na pozadí</string>
<string name="wake_battery_line">Některé telefony (Samsung, Xiaomi, Huawei, OnePlus a další) kvůli baterii zastavují aplikace na pozadí, a s nimi i budicí slovo. Zde vyjměte LLeMbas z optimalizace baterie; dontkillmyapp.com vysvětluje nastavení vašeho telefonu.</string>
<string name="wake_word_privacy">Před vyslovením slova nic neopustí telefon. Zvuk z mikrofonu jde jen do modulu pro budicí slovo v telefonu a neukládá se; po celou dobu naslouchání je vidět oznámení. Fráze jsou anglické; modul je sherpa-onnx (open source).</string>
<string name="wake_word_cost">Stojí to baterii: mikrofon zůstává zapnutý a procesor telefonu kontroluje každý okamžik zvuku, bez úsporného čipu, který používá vestavěný asistent. Pozastaví se v úsporném režimu, když je asistent otevřený, a pokud to nezměníte, i při zhasnuté obrazovce. Po restartu ho znovu spustíte klepnutím na oznámení.</string>
<string name="wake_listening_for">Naslouchám frázi „%1$s“</string>
<string name="wake_notification_line">Dokud ji neřeknete, nic neopustí telefon.</string>
<string name="wake_paused_screen">Budicí slovo pozastaveno: obrazovka je zhasnutá</string>
<string name="wake_paused_battery">Budicí slovo pozastaveno: je zapnutý úsporný režim</string>
<string name="wake_paused_assistant">Budicí slovo je pozastaveno, dokud je asistent otevřený</string>
<string name="wake_paused_microphone">Budicí slovo pozastaveno: mikrofon nebo modul není k dispozici</string>
<string name="wake_stop">Přestat naslouchat</string>
<string name="wake_heard">Slyšel jsem vás. Klepněte a ptejte se.</string>
<string name="wake_resume">Znovu naslouchat budicímu slovu</string>
<string name="wake_resume_line">Telefon se restartoval. Klepnutím znovu spustíte naslouchání.</string>
<string name="assist_notifications">Shrnout má oznámení</string>
<string name="assist_notifications_prompt">Shrň moje oznámení: co potřebuje mou pozornost?</string>
<string name="assist_notifications_phrases">moje oznámení|má oznámení|mých oznámení|moje notifikace</string>
<string name="notification_summaries">Shrnutí oznámení</string>
<string name="notification_summaries_switch">Dovolit asistentovi číst má oznámení, když o to požádám</string>
<string name="notification_summaries_line">Řekněte „shrň moje oznámení“, nebo klepněte na tlačítko v asistentovi.</string>
<string name="notification_access">Přístup k oznámením</string>
<string name="notification_access_on">Uděleno. Přepínač Androidu je v systémovém nastavení.</string>
<string name="notification_access_off">Zatím neuděleno. Klepnutím otevřete přepínač Androidu pro LLeMbas.</string>
<string name="notification_summaries_privacy">Ve výchozím stavu vypnuto. Když požádáte, text oznámení, která jsou v telefonu právě teď (aplikace, název, text), půjde s touto jedinou otázkou na vaši instanci a její model. Dřív se nic nečte, aplikace si nic neponechá a při zamčeném telefonu se nečte nic. Přístup k oznámením v Androidu dovolí aplikaci vidět každé oznámení, proto je na vás, zda ho dáte a zase vezmete.</string>
<string name="nav_app">Navigační aplikace</string>
<string name="nav_app_auto">Ta, která je nainstalovaná</string>
<string name="nav_app_google">Mapy Google</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Pokaždé se zeptat</string>
<string name="nav_app_not_installed">Není nainstalovaná</string>
<string name="osmand_info">Ptát se OsmAnd na trasu</string>
<string name="osmand_info_line">Umožní „přidat zastávku“ a hledání v okolí i u trasy nastavené přímo v OsmAnd: LLeMbas se OsmAnd zeptá, kde jste a kam trasa vede. Nejdřív LLeMbas povolte v OsmAnd (připojené aplikace, s polohou); OsmAnd dá vědět, pokud povoleno není.</string>
<string name="phone_actions_line">Model může nabídnout, že v telefonu něco udělá — nastaví budík, přidá událost, připraví zprávu, spustí trasu. Nic se nestane, dokud neklepnete na Provést na jeho kartě, a nikdy při zamčeném telefonu. Mapy Google spustí trasu s několika zastávkami, ale do běžící trasy zastávku nepřidají ani je nelze zastavit; OsmAnd to umí.</string>
<string name="action_card_title">Udělat to v telefonu?</string>
<string name="action_do">Provést</string>
<string name="action_running">Provádím…</string>
<string name="action_unlock">Nejdřív odemkněte telefon, pak klepněte na Provést.</string>
<string name="action_failed">Nepovedlo se: %1$s</string>
<string name="nav_app_pick">Ve které mapové aplikaci?</string>
<string name="action_google_add_stop">Mapy Google nepřidají zastávku do běžící trasy: spustí trasu znovu, přes zastávku.</string>
<string name="action_google_no_stop">Mapy Google nelze zastavit zvenčí: trasu ukončete v nich.</string>
<string name="action_line_clock">Nastaví to aplikace Hodiny.</string>
<string name="action_line_calendar">Otevře se kalendář s vyplněnou událostí; uložíte ji vy.</string>
<string name="action_line_draft">Otevře koncept; odešlete ho sami.</string>
<string name="action_line_dial">Otevře se vytáčení s číslem; hovor zahájíte vy.</string>
<string name="action_line_map">Trasu převezme %1$s.</string>
<string name="action_line_now">Stane se hned.</string>
<string name="action_line_settings">Otevře nastavení; změníte ho vy.</string>
<string name="action_line_automation">Spustí vaši automatizaci (Tasker, pokud není uvedena jiná aplikace).</string>
<string name="action_line_open">Otevře to.</string>
<string name="assist_recogniser_failed">Rozpoznávání řeči v telefonu se zastavilo. Zkuste to znovu nebo zvolte LLeMbas v Nastavení › Hlasový vstup.</string>
<string name="assistant_listens">Začít poslouchat, když se asistent otevře</string>
<string name="voice_input">Hlasový vstup</string>
@@ -401,4 +464,9 @@
<string name="voice_input_hint">Používá ho asistent i mikrofon v konverzaci. S LLeMbas asistent ukazuje slova s malým zpožděním a pauza je odešle, konverzace je zapíše, když přestanete; s rozpoznáváním v telefonu se objevují, jak mluvíte.</string>
<string name="share_sending">Odesílá se do LLeMbas…</string>
<string name="share_default_prompt">Podívejte se na tohle.</string>
<string name="share_ask_hint">Co s tím má LLeMbas udělat? (nepovinné)</string>
<string name="widget_hint">Zeptejte se na cokoli</string>
<string name="widget_speak">Mluvit</string>
<string name="widget_description">Ptejte se hlasem nebo textem, nebo pokračujte v poslední konverzaci s asistentem. Neukazuje nic z vašeho účtu.</string>
<string name="shortcut_last">Poslední chat</string>
</resources>
+69 -1
View File
@@ -377,7 +377,6 @@
<string name="assist_quick_explain_prompt">Erkläre, was auf meinem Bildschirm ist.</string>
<string name="assist_continue">Letzten Chat fortsetzen</string>
<string name="assist_help">Halten Sie die Ein-/Aus-Taste, um den Assistenten über jeder App zu öffnen, oder nutzen Sie die Kachel in den Schnelleinstellungen.</string>
<string name="assist_no_wake_word">Es gibt kein Aktivierungswort: Auf normalem Android ist das Lauschen darauf dem im Telefon eingebauten Assistenten vorbehalten.</string>
<string name="assist_connecting">Verbinden…</string>
<string name="assist_offline">%1$s ist nicht erreichbar</string>
<string name="assist_no_model">Kein Modell</string>
@@ -390,6 +389,70 @@
<string name="assist_say_it">Sprechen Sie, dann kurz Pause</string>
<string name="assist_type">Lieber tippen</string>
<string name="assist_writing_down">Ihr Gesagtes wird aufgeschrieben…</string>
<string name="assist_conversation">Im Gespräch</string>
<string name="assist_conversation_line">Nach jeder Antwort höre ich wieder zu. Sag „Stopp“, um zu beenden.</string>
<string name="assist_conversation_end">Beenden</string>
<string name="assist_stop_words">stopp|stop|das wars|das war\'s|das ist alles|genug|ende|tschüss|auf wiedersehen|danke das wars|abbrechen</string>
<string name="assistant_conversation">Ein gesprochenes Gespräch fortführen</string>
<string name="assistant_conversation_line">Nachdem eine gesprochene Antwort vorgelesen wurde, hört der Assistent wieder zu — bis du „Stopp“ sagst, auf Beenden tippst oder ein paar Sekunden nichts sagst. Funktioniert mit einem Headset.</string>
<string name="assist_wake_word_hint">Kein Aktivierungswort, außer du willst eines: Einstellungen › Assistent › Aktivierungswort schaltet das eigene von LLeMbas ein, auf diesem Telefon.</string>
<string name="channel_wake">Aktivierungswort</string>
<string name="wake_word">Aktivierungswort</string>
<string name="wake_word_listen">Auf ein Aktivierungswort hören</string>
<string name="wake_word_line">Standardmäßig aus. Sag den Satz, und der Assistent öffnet sich zuhörend über der App auf dem Bildschirm.</string>
<string name="wake_word_unavailable">Nicht in diesem Build. Der F-Droid-Build hat keine Aktivierungswort-Engine, weil F-Droid jede Bibliothek aus dem Quellcode baut; der Build von llembas.eu hat eine.</string>
<string name="wake_screen_only">Nur bei eingeschaltetem Bildschirm</string>
<string name="wake_screen_only_line">Aus: Es hört auch bei ausgeschaltetem Bildschirm zu, was mehr Akku kostet.</string>
<string name="wake_battery">Im Hintergrund laufen lassen</string>
<string name="wake_battery_line">Manche Telefone (Samsung, Xiaomi, Huawei, OnePlus und andere) beenden Hintergrund-Apps, um Akku zu sparen, und damit auch das Aktivierungswort. Nimm LLeMbas hier von der Akku-Optimierung aus; dontkillmyapp.com erklärt die Einstellungen deines Telefons.</string>
<string name="wake_word_privacy">Vor dem Wort verlässt nichts das Telefon. Der Ton des Mikrofons geht nur an die Aktivierungswort-Engine auf dem Telefon und wird nicht gespeichert; die Benachrichtigung bleibt sichtbar, solange es zuhört. Die Sätze sind englisch; die Engine ist sherpa-onnx (Open Source).</string>
<string name="wake_word_cost">Es kostet Akku: Das Mikrofon bleibt an, und der Prozessor des Telefons prüft jeden Moment Ton, ohne den Stromspar-Chip, den der eingebaute Assistent nutzt. Es pausiert im Energiesparmodus, während der Assistent offen ist und, wenn du es nicht änderst, bei ausgeschaltetem Bildschirm. Nach einem Neustart tippe auf seine Benachrichtigung, um es wieder zu starten.</string>
<string name="wake_listening_for">Hört auf „%1$s“</string>
<string name="wake_notification_line">Bis du es sagst, verlässt nichts das Telefon.</string>
<string name="wake_paused_screen">Aktivierungswort pausiert: Bildschirm aus</string>
<string name="wake_paused_battery">Aktivierungswort pausiert: Energiesparmodus ist an</string>
<string name="wake_paused_assistant">Aktivierungswort pausiert, solange der Assistent offen ist</string>
<string name="wake_paused_microphone">Aktivierungswort pausiert: Mikrofon oder Engine nicht verfügbar</string>
<string name="wake_stop">Nicht mehr zuhören</string>
<string name="wake_heard">Gehört. Tippe, um zu fragen.</string>
<string name="wake_resume">Wieder auf das Aktivierungswort hören</string>
<string name="wake_resume_line">Das Telefon wurde neu gestartet. Tippe, um wieder zuzuhören.</string>
<string name="assist_notifications">Meine Benachrichtigungen zusammenfassen</string>
<string name="assist_notifications_prompt">Fasse meine Benachrichtigungen zusammen: Was braucht meine Aufmerksamkeit?</string>
<string name="assist_notifications_phrases">meine benachrichtigungen|meinen benachrichtigungen|meiner benachrichtigungen</string>
<string name="notification_summaries">Zusammenfassungen der Benachrichtigungen</string>
<string name="notification_summaries_switch">Den Assistenten meine Benachrichtigungen lesen lassen, wenn ich frage</string>
<string name="notification_summaries_line">Sag „fasse meine Benachrichtigungen zusammen“ oder tippe auf den Chip im Assistenten.</string>
<string name="notification_access">Zugriff auf Benachrichtigungen</string>
<string name="notification_access_on">Erteilt. Der Schalter dafür ist in den Android-Einstellungen.</string>
<string name="notification_access_off">Noch nicht erteilt. Tippe, um den Android-Schalter für LLeMbas zu öffnen.</string>
<string name="notification_summaries_privacy">Standardmäßig aus. Wenn du fragst, geht der Text der Benachrichtigungen, die gerade auf deinem Telefon sind (App, Titel, Text), mit dieser einen Frage an deine Instanz und ihr Modell. Vorher wird nichts gelesen, die App behält nichts davon, und bei gesperrtem Telefon wird nichts gelesen. Der Benachrichtigungszugriff von Android lässt eine App jede Benachrichtigung sehen; ihn zu erteilen und zu entziehen liegt bei dir.</string>
<string name="nav_app">Navigations-App</string>
<string name="nav_app_auto">Die installierte</string>
<string name="nav_app_google">Google Maps</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Jedes Mal fragen</string>
<string name="nav_app_not_installed">Nicht installiert</string>
<string name="osmand_info">OsmAnd nach der Route fragen</string>
<string name="osmand_info_line">Damit „Zwischenstopp hinzufügen“ und die Suche in der Nähe auch mit einer in OsmAnd geplanten Route gehen: LLeMbas fragt OsmAnd, wo du bist und wohin die Route führt. Erlaube LLeMbas zuerst in OsmAnd (verbundene Apps, mit Standort); OsmAnd sagt Bescheid, wenn es nicht erlaubt ist.</string>
<string name="phone_actions_line">Ein Modell kann anbieten, etwas auf diesem Telefon zu tun — einen Wecker stellen, einen Termin eintragen, eine Nachricht entwerfen, eine Route starten. Nichts passiert, bevor du auf seiner Karte auf Ausführen tippst, und nie bei gesperrtem Telefon. Google Maps startet eine Route mit ein paar Stopps, kann aber keinen in eine laufende Route einfügen und nicht angehalten werden; OsmAnd kann das.</string>
<string name="action_card_title">Das auf deinem Telefon tun?</string>
<string name="action_do">Ausführen</string>
<string name="action_running">Wird ausgeführt…</string>
<string name="action_unlock">Entsperre zuerst das Telefon und tippe dann auf Ausführen.</string>
<string name="action_failed">Hat nicht geklappt: %1$s</string>
<string name="nav_app_pick">Mit welcher Karten-App?</string>
<string name="action_google_add_stop">Google Maps kann keinen Stopp in eine laufende Route einfügen: Es startet die Route neu, über den Stopp.</string>
<string name="action_google_no_stop">Google Maps lässt sich nicht von außen anhalten: Beende die Route dort.</string>
<string name="action_line_clock">Die Uhr-App stellt es ein.</string>
<string name="action_line_calendar">Der Kalender öffnet sich mit dem ausgefüllten Termin; du speicherst ihn.</string>
<string name="action_line_draft">Öffnet einen Entwurf; du sendest ihn selbst.</string>
<string name="action_line_dial">Die Telefon-App öffnet sich mit der Nummer; du rufst an.</string>
<string name="action_line_map">%1$s übernimmt die Route.</string>
<string name="action_line_now">Passiert sofort.</string>
<string name="action_line_settings">Öffnet die Einstellung; du änderst sie.</string>
<string name="action_line_automation">Startet deine Automatisierung (Tasker, wenn keine andere App genannt ist).</string>
<string name="action_line_open">Öffnet es.</string>
<string name="assist_recogniser_failed">Die Spracherkennung des Telefons hat angehalten. Versuchen Sie es erneut oder wählen Sie LLeMbas unter Einstellungen › Spracheingabe.</string>
<string name="assistant_listens">Beim Öffnen des Assistenten zuhören</string>
<string name="voice_input">Spracheingabe</string>
@@ -401,4 +464,9 @@
<string name="voice_input_hint">Wird vom Assistenten und vom Mikrofon im Chat genutzt. Mit LLeMbas zeigt der Assistent die Wörter einen Moment später, und eine Pause sendet sie, ein Chat schreibt sie auf, wenn Sie aufhören; mit der Erkennung des Telefons erscheinen sie beim Sprechen.</string>
<string name="share_sending">Wird an LLeMbas gesendet…</string>
<string name="share_default_prompt">Schauen Sie sich das an.</string>
<string name="share_ask_hint">Was soll LLeMbas damit tun? (optional)</string>
<string name="widget_hint">Frag mich alles</string>
<string name="widget_speak">Sprechen</string>
<string name="widget_description">Per Sprache oder Text fragen oder den letzten Assistenten-Chat fortsetzen. Zeigt nichts aus Ihrem Konto.</string>
<string name="shortcut_last">Letzter Chat</string>
</resources>
+69 -1
View File
@@ -377,7 +377,6 @@
<string name="assist_quick_explain_prompt">Explica lo que hay en mi pantalla.</string>
<string name="assist_continue">Continuar el último chat</string>
<string name="assist_help">Mantenga pulsado el botón de encendido para abrir el asistente sobre cualquier app, o use el mosaico de Ajustes rápidos.</string>
<string name="assist_no_wake_word">No hay palabra de activación: en Android estándar, escucharla está reservado al asistente integrado en el teléfono.</string>
<string name="assist_connecting">Conectando…</string>
<string name="assist_offline">No se puede contactar con %1$s</string>
<string name="assist_no_model">Sin modelo</string>
@@ -390,6 +389,70 @@
<string name="assist_say_it">Dígalo y haga una pausa</string>
<string name="assist_type">Escribir en su lugar</string>
<string name="assist_writing_down">Escribiendo lo que ha dicho…</string>
<string name="assist_conversation">En conversación</string>
<string name="assist_conversation_line">Vuelvo a escuchar después de cada respuesta. Di «para» para terminar.</string>
<string name="assist_conversation_end">Terminar</string>
<string name="assist_stop_words">para|stop|basta|eso es todo|ya está|adiós|terminar|fin|gracias eso es todo|cancelar</string>
<string name="assistant_conversation">Mantener una conversación hablada</string>
<string name="assistant_conversation_line">Después de leer en voz alta una respuesta hablada, el asistente vuelve a escuchar, hasta que digas «para», toques Terminar o no digas nada durante unos segundos. Funciona con auriculares.</string>
<string name="assist_wake_word_hint">Sin palabra de activación salvo que quieras una: Ajustes › Asistente › Palabra de activación activa la propia de LLeMbas, en este teléfono.</string>
<string name="channel_wake">Palabra de activación</string>
<string name="wake_word">Palabra de activación</string>
<string name="wake_word_listen">Escuchar una palabra de activación</string>
<string name="wake_word_line">Desactivado por defecto. Di la frase y el asistente se abre escuchando, sobre la app que esté en pantalla.</string>
<string name="wake_word_unavailable">No en esta versión. La versión de F-Droid no tiene motor de palabra de activación, porque F-Droid compila cada biblioteca desde el código fuente; la de llembas.eu sí lo tiene.</string>
<string name="wake_screen_only">Solo con la pantalla encendida</string>
<string name="wake_screen_only_line">Desactivado: también escucha con la pantalla apagada, con más gasto de batería.</string>
<string name="wake_battery">Dejar que funcione en segundo plano</string>
<string name="wake_battery_line">Algunos teléfonos (Samsung, Xiaomi, Huawei, OnePlus y otros) detienen las apps en segundo plano para ahorrar batería, y con ellas la palabra de activación. Excluye aquí a LLeMbas de la optimización de batería; dontkillmyapp.com explica los ajustes de tu teléfono.</string>
<string name="wake_word_privacy">Nada sale del teléfono antes de la palabra. El sonido del micrófono va solo al motor de palabra de activación del teléfono y no se guarda; la notificación se mantiene mientras escucha. Las frases están en inglés; el motor es sherpa-onnx (código abierto).</string>
<string name="wake_word_cost">Gasta batería: el micrófono sigue encendido y el procesador del teléfono revisa cada instante de sonido, sin el chip de bajo consumo que usa el asistente integrado. Se pausa en ahorro de batería, mientras el asistente está abierto y, salvo que lo cambies, con la pantalla apagada. Tras reiniciar, toca su notificación para volver a iniciarlo.</string>
<string name="wake_listening_for">Escuchando «%1$s»</string>
<string name="wake_notification_line">Nada sale del teléfono hasta que lo digas.</string>
<string name="wake_paused_screen">Palabra de activación en pausa: la pantalla está apagada</string>
<string name="wake_paused_battery">Palabra de activación en pausa: ahorro de batería activado</string>
<string name="wake_paused_assistant">Palabra de activación en pausa mientras el asistente está abierto</string>
<string name="wake_paused_microphone">Palabra de activación en pausa: el micrófono o el motor no están disponibles</string>
<string name="wake_stop">Dejar de escuchar</string>
<string name="wake_heard">Te he oído. Toca para preguntar.</string>
<string name="wake_resume">Volver a escuchar la palabra de activación</string>
<string name="wake_resume_line">El teléfono se reinició. Toca para volver a escuchar.</string>
<string name="assist_notifications">Resumir mis notificaciones</string>
<string name="assist_notifications_prompt">Resume mis notificaciones: ¿qué necesita mi atención?</string>
<string name="assist_notifications_phrases">mis notificaciones</string>
<string name="notification_summaries">Resúmenes de notificaciones</string>
<string name="notification_summaries_switch">Dejar que el asistente lea mis notificaciones cuando lo pida</string>
<string name="notification_summaries_line">Pide «resume mis notificaciones» o toca el botón en el asistente.</string>
<string name="notification_access">Acceso a notificaciones</string>
<string name="notification_access_on">Concedido. El interruptor de Android está en los ajustes del sistema.</string>
<string name="notification_access_off">Aún no concedido. Toca para abrir el interruptor de Android para LLeMbas.</string>
<string name="notification_summaries_privacy">Desactivado por defecto. Cuando lo pides, el texto de las notificaciones que hay ahora en tu teléfono (app, título, texto) va con esa única pregunta a tu instancia y su modelo. No se lee nada antes, la app no guarda nada y no se lee nada con el teléfono bloqueado. El acceso a notificaciones de Android permite a una app ver todas las notificaciones; darlo y retirarlo es cosa tuya.</string>
<string name="nav_app">App de navegación</string>
<string name="nav_app_auto">La que esté instalada</string>
<string name="nav_app_google">Google Maps</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Preguntar cada vez</string>
<string name="nav_app_not_installed">No instalada</string>
<string name="osmand_info">Preguntar a OsmAnd por la ruta</string>
<string name="osmand_info_line">Permite «añadir una parada» y buscar cerca de ti con una ruta creada en el propio OsmAnd: LLeMbas pregunta a OsmAnd dónde estás y adónde va la ruta. Primero permite LLeMbas en OsmAnd (apps conectadas, con ubicación); OsmAnd te avisa si no está permitido.</string>
<string name="phone_actions_line">Un modelo puede ofrecer hacer cosas en este teléfono: poner una alarma, añadir un evento, redactar un mensaje, iniciar una ruta. No pasa nada hasta que tocas Hacerlo en su tarjeta, y nunca con el teléfono bloqueado. Google Maps inicia una ruta con unas pocas paradas, pero no puede añadir una a una ruta en curso ni detenerse a petición; OsmAnd sí.</string>
<string name="action_card_title">¿Hacer esto en tu teléfono?</string>
<string name="action_do">Hacerlo</string>
<string name="action_running">Haciéndolo…</string>
<string name="action_unlock">Desbloquea primero el teléfono y luego toca Hacerlo.</string>
<string name="action_failed">No funcionó: %1$s</string>
<string name="nav_app_pick">¿Con qué app de mapas?</string>
<string name="action_google_add_stop">Google Maps no puede añadir una parada a una ruta en curso: vuelve a iniciar la ruta, pasando por la parada.</string>
<string name="action_google_no_stop">A Google Maps no se le puede pedir que pare: termina la ruta allí.</string>
<string name="action_line_clock">La app de reloj lo programa.</string>
<string name="action_line_calendar">El calendario se abre con el evento rellenado; tú lo guardas.</string>
<string name="action_line_draft">Abre un borrador; lo envías tú.</string>
<string name="action_line_dial">El marcador se abre con el número; tú haces la llamada.</string>
<string name="action_line_map">%1$s se encarga de la ruta.</string>
<string name="action_line_now">Ocurre al instante.</string>
<string name="action_line_settings">Abre el ajuste; tú lo cambias.</string>
<string name="action_line_automation">Ejecuta tu automatización (Tasker salvo que se indique otra app).</string>
<string name="action_line_open">Lo abre.</string>
<string name="assist_recogniser_failed">El reconocimiento de voz del teléfono se detuvo. Inténtelo de nuevo o elija LLeMbas en Ajustes › Entrada de voz.</string>
<string name="assistant_listens">Empezar a escuchar al abrir el asistente</string>
<string name="voice_input">Entrada de voz</string>
@@ -401,4 +464,9 @@
<string name="voice_input_hint">La usan el asistente y el micrófono de un chat. Con LLeMbas el asistente muestra las palabras un momento después y una pausa las envía, y un chat las escribe cuando usted para; con el reconocimiento del teléfono aparecen mientras habla.</string>
<string name="share_sending">Enviando a LLeMbas…</string>
<string name="share_default_prompt">Échele un vistazo a esto.</string>
<string name="share_ask_hint">¿Qué debe hacer LLeMbas con esto? (opcional)</string>
<string name="widget_hint">Pregunta lo que quieras</string>
<string name="widget_speak">Hablar</string>
<string name="widget_description">Pregunta por voz o por texto, o continúa el último chat del asistente. No muestra nada de tu cuenta.</string>
<string name="shortcut_last">Último chat</string>
</resources>
+69 -1
View File
@@ -377,7 +377,6 @@
<string name="assist_quick_explain_prompt">Explique ce qui est sur mon écran.</string>
<string name="assist_continue">Reprendre la dernière conversation</string>
<string name="assist_help">Maintenez le bouton marche/arrêt pour ouvrir l’assistant par-dessus n’importe quelle app, ou utilisez la tuile des Réglages rapides.</string>
<string name="assist_no_wake_word">Pas de mot d’activation : sur Android standard, l’écoute d’un tel mot est réservée à l’assistant intégré au téléphone.</string>
<string name="assist_connecting">Connexion…</string>
<string name="assist_offline">%1$s est injoignable</string>
<string name="assist_no_model">Aucun modèle</string>
@@ -390,6 +389,70 @@
<string name="assist_say_it">Dites-le, puis marquez une pause</string>
<string name="assist_type">Taper plutôt</string>
<string name="assist_writing_down">Transcription de ce que vous avez dit…</string>
<string name="assist_conversation">En conversation</string>
<string name="assist_conversation_line">J’écoute à nouveau après chaque réponse. Dites « stop » pour arrêter.</string>
<string name="assist_conversation_end">Terminer</string>
<string name="assist_stop_words">stop|arrête|c\'est tout|ça suffit|au revoir|fin|terminé|merci c\'est tout|annuler</string>
<string name="assistant_conversation">Poursuivre une conversation orale</string>
<string name="assistant_conversation_line">Après la lecture d’une réponse orale, l’assistant écoute à nouveau — jusqu’à ce que vous disiez « stop », touchiez Terminer ou ne disiez rien pendant quelques secondes. Fonctionne avec un casque.</string>
<string name="assist_wake_word_hint">Pas de mot d’activation sauf si vous en voulez un : Paramètres › Assistant › Mot d’activation active celui de LLeMbas, sur ce téléphone.</string>
<string name="channel_wake">Mot d’activation</string>
<string name="wake_word">Mot d’activation</string>
<string name="wake_word_listen">Écouter un mot d’activation</string>
<string name="wake_word_line">Désactivé par défaut. Dites la phrase et l’assistant s’ouvre en écoute, par-dessus l’app à l’écran.</string>
<string name="wake_word_unavailable">Pas dans cette version. La version F-Droid n’a pas de moteur de mot d’activation, car F-Droid compile chaque bibliothèque depuis les sources ; celle de llembas.eu en a un.</string>
<string name="wake_screen_only">Seulement écran allumé</string>
<string name="wake_screen_only_line">Désactivé : il écoute aussi écran éteint, au prix de plus de batterie.</string>
<string name="wake_battery">Le laisser tourner en arrière-plan</string>
<string name="wake_battery_line">Certains téléphones (Samsung, Xiaomi, Huawei, OnePlus et d’autres) arrêtent les apps en arrière-plan pour économiser la batterie, et le mot d’activation avec. Exemptez ici LLeMbas de l’optimisation de la batterie ; dontkillmyapp.com explique les réglages de votre téléphone.</string>
<string name="wake_word_privacy">Rien ne quitte le téléphone avant le mot. Le son du micro ne va qu’au moteur de mot d’activation du téléphone et n’est pas conservé ; la notification reste affichée tant qu’il écoute. Les phrases sont en anglais ; le moteur est sherpa-onnx (open source).</string>
<string name="wake_word_cost">Cela consomme de la batterie : le micro reste allumé et le processeur du téléphone examine chaque instant de son, sans la puce basse consommation de l’assistant intégré. Il se met en pause en économie de batterie, quand l’assistant est ouvert et, sauf si vous le changez, écran éteint. Après un redémarrage, touchez sa notification pour le relancer.</string>
<string name="wake_listening_for">À l’écoute de « %1$s »</string>
<string name="wake_notification_line">Rien ne quitte le téléphone avant que vous le disiez.</string>
<string name="wake_paused_screen">Mot d’activation en pause : écran éteint</string>
<string name="wake_paused_battery">Mot d’activation en pause : économiseur de batterie activé</string>
<string name="wake_paused_assistant">Mot d’activation en pause pendant que l’assistant est ouvert</string>
<string name="wake_paused_microphone">Mot d’activation en pause : micro ou moteur indisponible</string>
<string name="wake_stop">Arrêter l’écoute</string>
<string name="wake_heard">Entendu. Touchez pour demander.</string>
<string name="wake_resume">Écouter à nouveau le mot d’activation</string>
<string name="wake_resume_line">Le téléphone a redémarré. Touchez pour reprendre l’écoute.</string>
<string name="assist_notifications">Résumer mes notifications</string>
<string name="assist_notifications_prompt">Résume mes notifications : qu’est-ce qui demande mon attention ?</string>
<string name="assist_notifications_phrases">mes notifications</string>
<string name="notification_summaries">Résumés des notifications</string>
<string name="notification_summaries_switch">Laisser l’assistant lire mes notifications quand je le demande</string>
<string name="notification_summaries_line">Demandez « résume mes notifications », ou touchez la puce dans l’assistant.</string>
<string name="notification_access">Accès aux notifications</string>
<string name="notification_access_on">Accordé. L’interrupteur d’Android est dans les paramètres du système.</string>
<string name="notification_access_off">Pas encore accordé. Touchez pour ouvrir l’interrupteur d’Android pour LLeMbas.</string>
<string name="notification_summaries_privacy">Désactivé par défaut. Quand vous le demandez, le texte des notifications présentes sur votre téléphone (app, titre, texte) part avec cette seule question vers votre instance et son modèle. Rien n’est lu avant, l’app n’en garde rien, et rien n’est lu téléphone verrouillé. L’accès aux notifications d’Android permet à une app de voir toutes les notifications : c’est à vous de l’accorder et de le retirer.</string>
<string name="nav_app">App de navigation</string>
<string name="nav_app_auto">Celle qui est installée</string>
<string name="nav_app_google">Google Maps</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Demander à chaque fois</string>
<string name="nav_app_not_installed">Non installée</string>
<string name="osmand_info">Demander l’itinéraire à OsmAnd</string>
<string name="osmand_info_line">Permet « ajouter un arrêt » et la recherche à proximité avec un itinéraire créé dans OsmAnd même : LLeMbas demande à OsmAnd où vous êtes et où va l’itinéraire. Autorisez d’abord LLeMbas dans OsmAnd (apps connectées, avec la position) ; OsmAnd vous prévient sinon.</string>
<string name="phone_actions_line">Un modèle peut proposer de faire des choses sur ce téléphone : régler une alarme, ajouter un événement, rédiger un message, lancer un itinéraire. Rien ne se passe tant que vous ne touchez pas Le faire sur sa carte, et jamais téléphone verrouillé. Google Maps lance un itinéraire avec quelques arrêts mais ne peut ni en ajouter à un itinéraire en cours ni être arrêté ; OsmAnd le peut.</string>
<string name="action_card_title">Faire ceci sur votre téléphone ?</string>
<string name="action_do">Le faire</string>
<string name="action_running">En cours…</string>
<string name="action_unlock">Déverrouillez d’abord le téléphone, puis touchez Le faire.</string>
<string name="action_failed">Cela n’a pas marché : %1$s</string>
<string name="nav_app_pick">Avec quelle app de cartes ?</string>
<string name="action_google_add_stop">Google Maps ne peut pas ajouter d’arrêt à un itinéraire en cours : il relance l’itinéraire, par l’arrêt.</string>
<string name="action_google_no_stop">On ne peut pas dire à Google Maps d’arrêter : terminez l’itinéraire dans l’app.</string>
<string name="action_line_clock">L’app Horloge le règle.</string>
<string name="action_line_calendar">Le calendrier s’ouvre avec l’événement rempli ; vous l’enregistrez.</string>
<string name="action_line_draft">Ouvre un brouillon ; vous l’envoyez vous-même.</string>
<string name="action_line_dial">Le clavier s’ouvre avec le numéro ; vous lancez l’appel.</string>
<string name="action_line_map">%1$s prend l’itinéraire.</string>
<string name="action_line_now">Se fait aussitôt.</string>
<string name="action_line_settings">Ouvre le réglage ; vous le changez.</string>
<string name="action_line_automation">Lance votre automatisation (Tasker sauf si une autre app est nommée).</string>
<string name="action_line_open">L’ouvre.</string>
<string name="assist_recogniser_failed">La reconnaissance vocale du téléphone s’est arrêtée. Réessayez, ou choisissez LLeMbas dans Réglages › Saisie vocale.</string>
<string name="assistant_listens">Écouter dès l’ouverture de l’assistant</string>
<string name="voice_input">Saisie vocale</string>
@@ -401,4 +464,9 @@
<string name="voice_input_hint">Utilisée par l’assistant et par le micro d’une conversation. Avec LLeMbas, l’assistant affiche les mots avec un léger décalage et une pause les envoie, et une conversation les écrit quand vous vous arrêtez ; avec la reconnaissance du téléphone, ils apparaissent pendant que vous parlez.</string>
<string name="share_sending">Envoi à LLeMbas…</string>
<string name="share_default_prompt">Jetez un œil à ceci.</string>
<string name="share_ask_hint">Que doit en faire LLeMbas ? (facultatif)</string>
<string name="widget_hint">Posez une question</string>
<string name="widget_speak">Parler</string>
<string name="widget_description">Demandez à la voix ou par écrit, ou reprenez la dernière discussion de l’assistant. N’affiche rien de votre compte.</string>
<string name="shortcut_last">Dernière discussion</string>
</resources>
+69 -1
View File
@@ -377,7 +377,6 @@
<string name="assist_quick_explain_prompt">Magyarázd el, mi van a képernyőmön.</string>
<string name="assist_continue">Az utolsó csevegés folytatása</string>
<string name="assist_help">Tartsa lenyomva a bekapcsológombot, hogy bármely alkalmazás fölött megnyissa az asszisztenst, vagy használja a Gyorsbeállítások csempét.</string>
<string name="assist_no_wake_word">Ébresztőszó nincs: a gyári Androidon az ébresztőszó figyelése a telefonba épített asszisztensé.</string>
<string name="assist_connecting">Csatlakozás…</string>
<string name="assist_offline">%1$s nem érhető el</string>
<string name="assist_no_model">Nincs modell</string>
@@ -390,6 +389,70 @@
<string name="assist_say_it">Mondja, aztán tartson szünetet</string>
<string name="assist_type">Inkább gépelés</string>
<string name="assist_writing_down">Lejegyzem, amit mondott…</string>
<string name="assist_conversation">Beszélgetés</string>
<string name="assist_conversation_line">Minden válasz után újra figyelek. A befejezéshez mondd: „állj”.</string>
<string name="assist_conversation_end">Befejezés</string>
<string name="assist_stop_words">állj|stop|ennyi|ennyi volt|elég|vége|viszlát|köszönöm ennyi|mégse</string>
<string name="assistant_conversation">Szóbeli beszélgetés folytatása</string>
<string name="assistant_conversation_line">Egy szóbeli válasz felolvasása után az asszisztens újra figyel — amíg nem mondod, hogy „állj”, nem koppintasz a Befejezésre, vagy néhány másodpercig nem szólsz. Headsettel is működik.</string>
<string name="assist_wake_word_hint">Nincs ébresztőszó, hacsak nem kérsz: Beállítások › Asszisztens › Ébresztőszó bekapcsolja a LLeMbas sajátját, ezen a telefonon.</string>
<string name="channel_wake">Ébresztőszó</string>
<string name="wake_word">Ébresztőszó</string>
<string name="wake_word_listen">Ébresztőszó figyelése</string>
<string name="wake_word_line">Alapból ki van kapcsolva. Mondd ki a kifejezést, és az asszisztens figyelve megnyílik a képernyőn lévő alkalmazás fölött.</string>
<string name="wake_word_unavailable">Ebben a változatban nincs. Az F-Droid-változatban nincs ébresztőszó-motor, mert az F-Droid minden könyvtárat forrásból fordít; a llembas.eu-s változatban van.</string>
<string name="wake_screen_only">Csak bekapcsolt képernyőnél</string>
<string name="wake_screen_only_line">Kikapcsolva kikapcsolt képernyőnél is figyel, ami több akkumulátort fogyaszt.</string>
<string name="wake_battery">Futhasson a háttérben</string>
<string name="wake_battery_line">Egyes telefonok (Samsung, Xiaomi, Huawei, OnePlus és mások) az akkumulátor kímélése miatt leállítják a háttéralkalmazásokat, és velük az ébresztőszót is. Itt vedd ki a LLeMbast az akkumulátor-optimalizálásból; a dontkillmyapp.com elmagyarázza a telefonod beállításait.</string>
<string name="wake_word_privacy">A szó előtt semmi nem hagyja el a telefont. A mikrofon hangja csak a telefonon futó ébresztőszó-motorhoz jut, és nem tárolódik; amíg figyel, az értesítés végig látható. A kifejezések angolok; a motor a sherpa-onnx (nyílt forráskódú).</string>
<string name="wake_word_cost">Akkumulátorba kerül: a mikrofon bekapcsolva marad, és a telefon processzora minden hangpillanatot ellenőriz, a beépített asszisztens energiatakarékos chipje nélkül. Energiatakarékos módban, nyitott asszisztensnél és — ha nem változtatod meg — kikapcsolt képernyőnél szünetel. Újraindítás után koppints az értesítésére az újraindításhoz.</string>
<string name="wake_listening_for">Figyeli: „%1$s”</string>
<string name="wake_notification_line">Amíg ki nem mondod, semmi nem hagyja el a telefont.</string>
<string name="wake_paused_screen">Ébresztőszó szünetel: a képernyő ki van kapcsolva</string>
<string name="wake_paused_battery">Ébresztőszó szünetel: be van kapcsolva az energiatakarékos mód</string>
<string name="wake_paused_assistant">Az ébresztőszó szünetel, amíg az asszisztens nyitva van</string>
<string name="wake_paused_microphone">Ébresztőszó szünetel: a mikrofon vagy a motor nem érhető el</string>
<string name="wake_stop">Figyelés leállítása</string>
<string name="wake_heard">Hallottalak. Koppints a kérdezéshez.</string>
<string name="wake_resume">Ébresztőszó figyelése újra</string>
<string name="wake_resume_line">A telefon újraindult. Koppints a figyelés folytatásához.</string>
<string name="assist_notifications">Értesítéseim összefoglalása</string>
<string name="assist_notifications_prompt">Foglald össze az értesítéseimet: mi igényli a figyelmemet?</string>
<string name="assist_notifications_phrases">értesítéseim|értesítéseimet|az értesítéseimről</string>
<string name="notification_summaries">Értesítések összefoglalása</string>
<string name="notification_summaries_switch">Az asszisztens kérésemre elolvashatja az értesítéseimet</string>
<string name="notification_summaries_line">Kérd, hogy „foglald össze az értesítéseimet”, vagy koppints a gombra az asszisztensben.</string>
<string name="notification_access">Hozzáférés az értesítésekhez</string>
<string name="notification_access_on">Megadva. Az Android kapcsolója a rendszerbeállításokban van.</string>
<string name="notification_access_off">Még nincs megadva. Koppints az Android LLeMbas-kapcsolójának megnyitásához.</string>
<string name="notification_summaries_privacy">Alapból ki van kapcsolva. Ha kéred, a telefonon éppen látható értesítések szövege (alkalmazás, cím, szöveg) ezzel az egy kérdéssel együtt a példányodhoz és a modelljéhez kerül. Előtte semmit nem olvas, az alkalmazás semmit nem tart meg, és zárolt telefonnál semmit nem olvas. Az Android értesítés-hozzáférése minden értesítést láthatóvá tesz egy alkalmazásnak, ezért rajtad múlik, megadod-e, és visszavonod-e.</string>
<string name="nav_app">Navigációs alkalmazás</string>
<string name="nav_app_auto">Amelyik telepítve van</string>
<string name="nav_app_google">Google Térkép</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Mindig kérdezzen</string>
<string name="nav_app_not_installed">Nincs telepítve</string>
<string name="osmand_info">Útvonal lekérdezése az OsmAndtól</string>
<string name="osmand_info_line">Így a „megálló hozzáadása” és a közeli keresés az OsmAndban beállított útvonallal is működik: a LLeMbas megkérdezi az OsmAndot, hol vagy és hová tart az útvonal. Előbb engedélyezd a LLeMbast az OsmAndban (csatlakoztatott alkalmazások, helyadattal); az OsmAnd szól, ha nincs engedélyezve.</string>
<string name="phone_actions_line">Egy modell felajánlhatja, hogy tesz valamit ezen a telefonon — ébresztőt állít, eseményt vesz fel, üzenetet fogalmaz, útvonalat indít. Semmi sem történik, amíg a kártyáján nem koppintasz a Mehet gombra, és zárolt telefonnál soha. A Google Térkép néhány megállós útvonalat indít, de futó útvonalhoz nem ad megállót és nem állítható le; az OsmAnd igen.</string>
<string name="action_card_title">Megtegyem ezt a telefonodon?</string>
<string name="action_do">Mehet</string>
<string name="action_running">Folyamatban…</string>
<string name="action_unlock">Előbb oldd fel a telefont, aztán koppints a Mehet gombra.</string>
<string name="action_failed">Nem sikerült: %1$s</string>
<string name="nav_app_pick">Melyik térképalkalmazással?</string>
<string name="action_google_add_stop">A Google Térkép nem tud megállót adni egy futó útvonalhoz: újraindítja az útvonalat a megállón át.</string>
<string name="action_google_no_stop">A Google Térképet nem lehet kívülről leállítani: ott fejezd be az útvonalat.</string>
<string name="action_line_clock">Az Óra alkalmazás beállítja.</string>
<string name="action_line_calendar">Megnyílik a naptár a kitöltött eseménnyel; te mented el.</string>
<string name="action_line_draft">Megnyit egy piszkozatot; te küldöd el.</string>
<string name="action_line_dial">Megnyílik a tárcsázó a számmal; te indítod a hívást.</string>
<string name="action_line_map">Az útvonalat a(z) %1$s kapja.</string>
<string name="action_line_now">Azonnal megtörténik.</string>
<string name="action_line_settings">Megnyitja a beállítást; te módosítod.</string>
<string name="action_line_automation">Lefuttatja az automatizálásodat (Tasker, ha nincs más alkalmazás megadva).</string>
<string name="action_line_open">Megnyitja.</string>
<string name="assist_recogniser_failed">A telefon beszédfelismerője leállt. Próbálja újra, vagy válassza a LLeMbast a Beállítások › Hangbevitel alatt.</string>
<string name="assistant_listens">Hallgatás indítása az asszisztens megnyitásakor</string>
<string name="voice_input">Hangbevitel</string>
@@ -401,4 +464,9 @@
<string name="voice_input_hint">Az asszisztens és a csevegés mikrofonja használja. LLeMbasszal az asszisztens kis késéssel mutatja a szavakat, és egy szünet elküldi őket, a csevegés pedig akkor írja le őket, amikor abbahagyja; a telefon felismerőjével beszéd közben jelennek meg.</string>
<string name="share_sending">Küldés az LLeMbas-nak…</string>
<string name="share_default_prompt">Nézze meg ezt.</string>
<string name="share_ask_hint">Mit kezdjen vele a LLeMbas? (nem kötelező)</string>
<string name="widget_hint">Kérdezz bármit</string>
<string name="widget_speak">Beszéd</string>
<string name="widget_description">Kérdezz hanggal vagy szöveggel, vagy folytasd az asszisztens legutóbbi csevegését. A fiókodból semmit sem mutat.</string>
<string name="shortcut_last">Utolsó csevegés</string>
</resources>
+69 -1
View File
@@ -377,7 +377,6 @@
<string name="assist_quick_explain_prompt">Spiega cosa c’è sul mio schermo.</string>
<string name="assist_continue">Continua l’ultima chat</string>
<string name="assist_help">Tenga premuto il tasto di accensione per aprire l’assistente sopra qualsiasi app, oppure usi il riquadro delle Impostazioni rapide.</string>
<string name="assist_no_wake_word">Non c’è una parola di attivazione: su Android standard, l’ascolto di una tale parola è riservato all’assistente integrato nel telefono.</string>
<string name="assist_connecting">Connessione…</string>
<string name="assist_offline">%1$s non è raggiungibile</string>
<string name="assist_no_model">Nessun modello</string>
@@ -390,6 +389,70 @@
<string name="assist_say_it">Lo dica, poi faccia una pausa</string>
<string name="assist_type">Scrivi invece</string>
<string name="assist_writing_down">Trascrivo ciò che ha detto…</string>
<string name="assist_conversation">In conversazione</string>
<string name="assist_conversation_line">Ascolto di nuovo dopo ogni risposta. Di’ «basta» per finire.</string>
<string name="assist_conversation_end">Termina</string>
<string name="assist_stop_words">basta|stop|è tutto|fine|ciao|arrivederci|grazie è tutto|annulla|smetti</string>
<string name="assistant_conversation">Continuare una conversazione a voce</string>
<string name="assistant_conversation_line">Dopo aver letto ad alta voce una risposta a voce, l’assistente ascolta di nuovo, finché non dici «basta», tocchi Termina o non dici nulla per qualche secondo. Funziona con le cuffie.</string>
<string name="assist_wake_word_hint">Nessuna parola di attivazione, a meno che tu non la voglia: Impostazioni › Assistente › Parola di attivazione attiva quella di LLeMbas, su questo telefono.</string>
<string name="channel_wake">Parola di attivazione</string>
<string name="wake_word">Parola di attivazione</string>
<string name="wake_word_listen">Ascolta una parola di attivazione</string>
<string name="wake_word_line">Disattivata per impostazione predefinita. Di’ la frase e l’assistente si apre in ascolto, sopra l’app sullo schermo.</string>
<string name="wake_word_unavailable">Non in questa build. La build F-Droid non ha un motore per la parola di attivazione, perché F-Droid compila ogni libreria dal sorgente; la build di llembas.eu ce l’ha.</string>
<string name="wake_screen_only">Solo a schermo acceso</string>
<string name="wake_screen_only_line">Disattivato: ascolta anche a schermo spento, con più consumo di batteria.</string>
<string name="wake_battery">Lascialo funzionare in background</string>
<string name="wake_battery_line">Alcuni telefoni (Samsung, Xiaomi, Huawei, OnePlus e altri) fermano le app in background per risparmiare batteria, e con loro la parola di attivazione. Escludi qui LLeMbas dall’ottimizzazione della batteria; dontkillmyapp.com spiega le impostazioni del tuo telefono.</string>
<string name="wake_word_privacy">Niente lascia il telefono prima della parola. Il suono del microfono va solo al motore della parola di attivazione sul telefono e non viene conservato; la notifica resta visibile finché ascolta. Le frasi sono in inglese; il motore è sherpa-onnx (open source).</string>
<string name="wake_word_cost">Consuma batteria: il microfono resta acceso e il processore del telefono esamina ogni istante di suono, senza il chip a basso consumo usato dall’assistente integrato. Si mette in pausa con il risparmio energetico, mentre l’assistente è aperto e, se non lo cambi, a schermo spento. Dopo un riavvio, tocca la sua notifica per riavviarlo.</string>
<string name="wake_listening_for">In ascolto di «%1$s»</string>
<string name="wake_notification_line">Niente lascia il telefono finché non lo dici.</string>
<string name="wake_paused_screen">Parola di attivazione in pausa: schermo spento</string>
<string name="wake_paused_battery">Parola di attivazione in pausa: risparmio energetico attivo</string>
<string name="wake_paused_assistant">Parola di attivazione in pausa mentre l’assistente è aperto</string>
<string name="wake_paused_microphone">Parola di attivazione in pausa: microfono o motore non disponibili</string>
<string name="wake_stop">Smetti di ascoltare</string>
<string name="wake_heard">Ti ho sentito. Tocca per chiedere.</string>
<string name="wake_resume">Ascolta di nuovo la parola di attivazione</string>
<string name="wake_resume_line">Il telefono si è riavviato. Tocca per ricominciare ad ascoltare.</string>
<string name="assist_notifications">Riassumi le mie notifiche</string>
<string name="assist_notifications_prompt">Riassumi le mie notifiche: cosa richiede la mia attenzione?</string>
<string name="assist_notifications_phrases">le mie notifiche|mie notifiche</string>
<string name="notification_summaries">Riepiloghi delle notifiche</string>
<string name="notification_summaries_switch">Lascia che l’assistente legga le mie notifiche quando lo chiedo</string>
<string name="notification_summaries_line">Chiedi «riassumi le mie notifiche» o tocca il pulsante nell’assistente.</string>
<string name="notification_access">Accesso alle notifiche</string>
<string name="notification_access_on">Concesso. L’interruttore di Android è nelle impostazioni di sistema.</string>
<string name="notification_access_off">Non ancora concesso. Tocca per aprire l’interruttore di Android per LLeMbas.</string>
<string name="notification_summaries_privacy">Disattivato per impostazione predefinita. Quando lo chiedi, il testo delle notifiche presenti ora sul telefono (app, titolo, testo) va con quella sola domanda alla tua istanza e al suo modello. Prima non si legge nulla, l’app non conserva nulla e a telefono bloccato non si legge nulla. L’accesso alle notifiche di Android permette a un’app di vedere ogni notifica: concederlo e revocarlo spetta a te.</string>
<string name="nav_app">App di navigazione</string>
<string name="nav_app_auto">Quella installata</string>
<string name="nav_app_google">Google Maps</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Chiedi ogni volta</string>
<string name="nav_app_not_installed">Non installata</string>
<string name="osmand_info">Chiedi il percorso a OsmAnd</string>
<string name="osmand_info_line">Permette «aggiungi una tappa» e la ricerca nelle vicinanze anche con un percorso impostato in OsmAnd: LLeMbas chiede a OsmAnd dove sei e dove va il percorso. Prima consenti LLeMbas in OsmAnd (app collegate, con posizione); OsmAnd ti avvisa se non è consentito.</string>
<string name="phone_actions_line">Un modello può offrirsi di fare cose su questo telefono: impostare una sveglia, aggiungere un evento, preparare un messaggio, avviare un percorso. Non succede nulla finché non tocchi Fallo sulla sua scheda, e mai a telefono bloccato. Google Maps avvia un percorso con alcune tappe ma non può aggiungerne a un percorso in corso né essere fermato; OsmAnd sì.</string>
<string name="action_card_title">Farlo sul tuo telefono?</string>
<string name="action_do">Fallo</string>
<string name="action_running">In corso…</string>
<string name="action_unlock">Sblocca prima il telefono, poi tocca Fallo.</string>
<string name="action_failed">Non ha funzionato: %1$s</string>
<string name="nav_app_pick">Con quale app di mappe?</string>
<string name="action_google_add_stop">Google Maps non può aggiungere una tappa a un percorso in corso: riavvia il percorso passando per la tappa.</string>
<string name="action_google_no_stop">Non si può dire a Google Maps di fermarsi: termina il percorso lì.</string>
<string name="action_line_clock">Lo imposta l’app Orologio.</string>
<string name="action_line_calendar">Il calendario si apre con l’evento compilato; lo salvi tu.</string>
<string name="action_line_draft">Apre una bozza; la invii tu.</string>
<string name="action_line_dial">Il tastierino si apre con il numero; la chiamata la fai tu.</string>
<string name="action_line_map">Il percorso va a %1$s.</string>
<string name="action_line_now">Avviene subito.</string>
<string name="action_line_settings">Apre l’impostazione; la cambi tu.</string>
<string name="action_line_automation">Esegue la tua automazione (Tasker se non è indicata un’altra app).</string>
<string name="action_line_open">Lo apre.</string>
<string name="assist_recogniser_failed">Il riconoscimento vocale del telefono si è fermato. Riprovi, oppure scelga LLeMbas in Impostazioni › Input vocale.</string>
<string name="assistant_listens">Inizia ad ascoltare all’apertura dell’assistente</string>
<string name="voice_input">Input vocale</string>
@@ -401,4 +464,9 @@
<string name="voice_input_hint">La usano l’assistente e il microfono di una chat. Con LLeMbas l’assistente mostra le parole con un attimo di ritardo e una pausa le invia, e una chat le scrive quando si ferma; con il riconoscimento del telefono appaiono mentre parla.</string>
<string name="share_sending">Invio a LLeMbas…</string>
<string name="share_default_prompt">Dai un\'occhiata a questo.</string>
<string name="share_ask_hint">Cosa deve farne LLeMbas? (facoltativo)</string>
<string name="widget_hint">Chiedi qualsiasi cosa</string>
<string name="widget_speak">Parla</string>
<string name="widget_description">Chiedi a voce o per iscritto, o continua l’ultima chat dell’assistente. Non mostra nulla del tuo account.</string>
<string name="shortcut_last">Ultima chat</string>
</resources>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.10 (moria). Do not edit. -->
<resources>
<color name="token_bg">#FF0B0D10</color>
<color name="token_surface">#FF11151A</color>
<color name="token_surface_raised">#FF171C22</color>
<color name="token_border">#FF26303A</color>
<color name="token_ink">#FFE2E8EC</color>
<color name="token_ink_muted">#FFA6B2BC</color>
<color name="token_accent">#FF8FD8E8</color>
<color name="token_accent_ink">#FF061418</color>
<color name="token_accent_soft">#1F8FD8E8</color>
</resources>
+69 -1
View File
@@ -377,7 +377,6 @@
<string name="assist_quick_explain_prompt">Wyjaśnij, co jest na moim ekranie.</string>
<string name="assist_continue">Kontynuuj ostatni czat</string>
<string name="assist_help">Przytrzymaj przycisk zasilania, aby otworzyć asystenta nad dowolną aplikacją, albo użyj kafelka w Szybkich ustawieniach.</string>
<string name="assist_no_wake_word">Nie ma słowa wybudzającego: w zwykłym Androidzie nasłuchiwanie go jest zarezerwowane dla asystenta wbudowanego w telefon.</string>
<string name="assist_connecting">Łączenie…</string>
<string name="assist_offline">%1$s jest nieosiągalna</string>
<string name="assist_no_model">Brak modelu</string>
@@ -390,6 +389,70 @@
<string name="assist_say_it">Powiedz to i zrób pauzę</string>
<string name="assist_type">Zamiast tego pisz</string>
<string name="assist_writing_down">Zapisuję, co powiedziałeś…</string>
<string name="assist_conversation">Rozmowa</string>
<string name="assist_conversation_line">Po każdej odpowiedzi słucham znowu. Powiedz „stop”, aby zakończyć.</string>
<string name="assist_conversation_end">Zakończ</string>
<string name="assist_stop_words">stop|wystarczy|to wszystko|koniec|do widzenia|dzięki to wszystko|anuluj|przestań</string>
<string name="assistant_conversation">Prowadź rozmowę głosową</string>
<string name="assistant_conversation_line">Po odczytaniu odpowiedzi na głos asystent znów słucha — dopóki nie powiesz „stop”, nie dotkniesz Zakończ albo nie będziesz milczeć przez kilka sekund. Działa ze słuchawkami.</string>
<string name="assist_wake_word_hint">Bez słowa aktywującego, chyba że chcesz: Ustawienia › Asystent › Słowo aktywujące włącza własne słowo LLeMbas, na tym telefonie.</string>
<string name="channel_wake">Słowo aktywujące</string>
<string name="wake_word">Słowo aktywujące</string>
<string name="wake_word_listen">Nasłuchuj słowa aktywującego</string>
<string name="wake_word_line">Domyślnie wyłączone. Powiedz frazę, a asystent otworzy się i zacznie słuchać, nad aplikacją na ekranie.</string>
<string name="wake_word_unavailable">Nie w tej wersji. Wersja z F-Droid nie ma silnika słowa aktywującego, bo F-Droid buduje każdą bibliotekę ze źródeł; wersja z llembas.eu go ma.</string>
<string name="wake_screen_only">Tylko przy włączonym ekranie</string>
<string name="wake_screen_only_line">Wyłączone: słucha także przy wyłączonym ekranie, kosztem baterii.</string>
<string name="wake_battery">Pozwól działać w tle</string>
<string name="wake_battery_line">Niektóre telefony (Samsung, Xiaomi, Huawei, OnePlus i inne) zatrzymują aplikacje w tle, by oszczędzać baterię, a z nimi słowo aktywujące. Wyłącz tu LLeMbas z optymalizacji baterii; dontkillmyapp.com wyjaśnia ustawienia Twojego telefonu.</string>
<string name="wake_word_privacy">Nic nie opuszcza telefonu przed słowem. Dźwięk z mikrofonu trafia tylko do silnika słowa aktywującego w telefonie i nie jest zapisywany; powiadomienie jest widoczne przez cały czas nasłuchiwania. Frazy są po angielsku; silnik to sherpa-onnx (open source).</string>
<string name="wake_word_cost">Zużywa baterię: mikrofon pozostaje włączony, a procesor telefonu sprawdza każdą chwilę dźwięku, bez energooszczędnego układu, którego używa wbudowany asystent. Wstrzymuje się w trybie oszczędzania baterii, gdy asystent jest otwarty, i — jeśli tego nie zmienisz — przy wyłączonym ekranie. Po ponownym uruchomieniu dotknij jego powiadomienia, by znów zaczął.</string>
<string name="wake_listening_for">Nasłuchuje „%1$s”</string>
<string name="wake_notification_line">Nic nie opuszcza telefonu, dopóki tego nie powiesz.</string>
<string name="wake_paused_screen">Słowo aktywujące wstrzymane: ekran jest wyłączony</string>
<string name="wake_paused_battery">Słowo aktywujące wstrzymane: oszczędzanie baterii jest włączone</string>
<string name="wake_paused_assistant">Słowo aktywujące wstrzymane, gdy asystent jest otwarty</string>
<string name="wake_paused_microphone">Słowo aktywujące wstrzymane: mikrofon lub silnik jest niedostępny</string>
<string name="wake_stop">Przestań słuchać</string>
<string name="wake_heard">Słyszę. Dotknij, aby zapytać.</string>
<string name="wake_resume">Znów nasłuchuj słowa aktywującego</string>
<string name="wake_resume_line">Telefon uruchomił się ponownie. Dotknij, aby znów słuchać.</string>
<string name="assist_notifications">Podsumuj moje powiadomienia</string>
<string name="assist_notifications_prompt">Podsumuj moje powiadomienia: co wymaga mojej uwagi?</string>
<string name="assist_notifications_phrases">moje powiadomienia|moich powiadomień|moje notyfikacje</string>
<string name="notification_summaries">Podsumowania powiadomień</string>
<string name="notification_summaries_switch">Pozwól asystentowi czytać moje powiadomienia, gdy poproszę</string>
<string name="notification_summaries_line">Poproś „podsumuj moje powiadomienia” albo dotknij przycisku w asystencie.</string>
<string name="notification_access">Dostęp do powiadomień</string>
<string name="notification_access_on">Przyznany. Przełącznik Androida jest w ustawieniach systemu.</string>
<string name="notification_access_off">Jeszcze nie przyznany. Dotknij, aby otworzyć przełącznik Androida dla LLeMbas.</string>
<string name="notification_summaries_privacy">Domyślnie wyłączone. Gdy poprosisz, tekst powiadomień, które są teraz na telefonie (aplikacja, tytuł, treść), trafi z tym jednym pytaniem do Twojej instancji i jej modelu. Wcześniej nic nie jest czytane, aplikacja niczego nie zachowuje i nic nie jest czytane przy zablokowanym telefonie. Dostęp do powiadomień w Androidzie pozwala aplikacji widzieć każde powiadomienie, więc to Ty decydujesz, czy go dać i odebrać.</string>
<string name="nav_app">Aplikacja nawigacyjna</string>
<string name="nav_app_auto">Ta, która jest zainstalowana</string>
<string name="nav_app_google">Mapy Google</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Pytaj za każdym razem</string>
<string name="nav_app_not_installed">Nie zainstalowano</string>
<string name="osmand_info">Pytaj OsmAnd o trasę</string>
<string name="osmand_info_line">Pozwala „dodać przystanek” i szukać w pobliżu także przy trasie ustawionej w samym OsmAnd: LLeMbas pyta OsmAnd, gdzie jesteś i dokąd prowadzi trasa. Najpierw zezwól LLeMbas w OsmAnd (połączone aplikacje, z lokalizacją); OsmAnd poinformuje, jeśli nie ma zgody.</string>
<string name="phone_actions_line">Model może zaproponować zrobienie czegoś na tym telefonie — ustawienie budzika, dodanie wydarzenia, szkic wiadomości, start trasy. Nic się nie dzieje, dopóki nie dotkniesz Zrób to na jego karcie, i nigdy przy zablokowanym telefonie. Mapy Google uruchomią trasę z kilkoma przystankami, ale nie dodadzą przystanku do trwającej trasy ani nie dadzą się zatrzymać; OsmAnd potrafi.</string>
<string name="action_card_title">Zrobić to na telefonie?</string>
<string name="action_do">Zrób to</string>
<string name="action_running">Robię to…</string>
<string name="action_unlock">Najpierw odblokuj telefon, potem dotknij Zrób to.</string>
<string name="action_failed">Nie udało się: %1$s</string>
<string name="nav_app_pick">W której aplikacji map?</string>
<string name="action_google_add_stop">Mapy Google nie dodadzą przystanku do trwającej trasy: uruchomią trasę od nowa, przez przystanek.</string>
<string name="action_google_no_stop">Map Google nie da się zatrzymać z zewnątrz: zakończ trasę w nich.</string>
<string name="action_line_clock">Ustawi to aplikacja Zegar.</string>
<string name="action_line_calendar">Kalendarz otworzy się z wypełnionym wydarzeniem; Ty je zapiszesz.</string>
<string name="action_line_draft">Otwiera szkic; wysyłasz go sam.</string>
<string name="action_line_dial">Otworzy się wybieranie z numerem; połączenie rozpoczniesz Ty.</string>
<string name="action_line_map">Trasę przejmie %1$s.</string>
<string name="action_line_now">Dzieje się od razu.</string>
<string name="action_line_settings">Otwiera ustawienie; Ty je zmieniasz.</string>
<string name="action_line_automation">Uruchamia Twoją automatyzację (Tasker, chyba że podano inną aplikację).</string>
<string name="action_line_open">Otwiera to.</string>
<string name="assist_recogniser_failed">Rozpoznawanie mowy w telefonie przestało działać. Spróbuj ponownie albo wybierz LLeMbas w Ustawienia › Wprowadzanie głosowe.</string>
<string name="assistant_listens">Zacznij słuchać po otwarciu asystenta</string>
<string name="voice_input">Wprowadzanie głosowe</string>
@@ -401,4 +464,9 @@
<string name="voice_input_hint">Używa go asystent i mikrofon w czacie. Z LLeMbas asystent pokazuje słowa z lekkim opóźnieniem, a pauza je wysyła, czat zapisuje je, gdy przestaniesz; z rozpoznawaniem telefonu pojawiają się w trakcie mówienia.</string>
<string name="share_sending">Wysyłanie do LLeMbas…</string>
<string name="share_default_prompt">Zobacz to.</string>
<string name="share_ask_hint">Co LLeMbas ma z tym zrobić? (opcjonalnie)</string>
<string name="widget_hint">Zapytaj o cokolwiek</string>
<string name="widget_speak">Mów</string>
<string name="widget_description">Pytaj głosem lub tekstem albo kontynuuj ostatni czat asystenta. Nie pokazuje niczego z Twojego konta.</string>
<string name="shortcut_last">Ostatni czat</string>
</resources>
+69 -1
View File
@@ -377,7 +377,6 @@
<string name="assist_quick_explain_prompt">Vysvetli, čo je na mojej obrazovke.</string>
<string name="assist_continue">Pokračovať v poslednej konverzácii</string>
<string name="assist_help">Podržaním tlačidla napájania otvoríte asistenta nad ľubovoľnou aplikáciou; alebo použite dlaždicu v Rýchlych nastaveniach.</string>
<string name="assist_no_wake_word">Budiace slovo nie je: na bežnom Androide je počúvanie budiaceho slova vyhradené asistentovi zabudovanému v telefóne.</string>
<string name="assist_connecting">Pripája sa…</string>
<string name="assist_offline">%1$s je nedostupná</string>
<string name="assist_no_model">Žiadny model</string>
@@ -390,6 +389,70 @@
<string name="assist_say_it">Povedzte to a odmlčte sa</string>
<string name="assist_type">Radšej písať</string>
<string name="assist_writing_down">Zapisujem, čo ste povedali…</string>
<string name="assist_conversation">Rozhovor</string>
<string name="assist_conversation_line">Po každej odpovedi znova počúvam. Povedzte „stop“ a skončíme.</string>
<string name="assist_conversation_end">Ukončiť</string>
<string name="assist_stop_words">stop|dosť|to je všetko|koniec|dovidenia|ďakujem to je všetko|zrušiť|prestaň</string>
<string name="assistant_conversation">Pokračovať v hovorenom rozhovore</string>
<string name="assistant_conversation_line">Po prečítaní hovorenej odpovede asistent znova počúva — kým nepoviete „stop“, neťuknete na Ukončiť alebo pár sekúnd nič nepoviete. Funguje aj so slúchadlami.</string>
<string name="assist_wake_word_hint">Budiace slovo len ak chcete: Nastavenia › Asistent › Budiace slovo zapne vlastné slovo LLeMbas, priamo v tomto telefóne.</string>
<string name="channel_wake">Budiace slovo</string>
<string name="wake_word">Budiace slovo</string>
<string name="wake_word_listen">Počúvať budiace slovo</string>
<string name="wake_word_line">Predvolene vypnuté. Povedzte frázu a asistent sa otvorí a počúva, nad akoukoľvek aplikáciou na obrazovke.</string>
<string name="wake_word_unavailable">V tomto zostavení nie je. Zostavenie pre F-Droid nemá modul pre budiace slovo, pretože F-Droid zostavuje každú knižnicu zo zdrojov; zostavenie z llembas.eu ho má.</string>
<string name="wake_screen_only">Len pri zapnutej obrazovke</string>
<string name="wake_screen_only_line">Vypnuté: počúva aj pri zhasnutej obrazovke, za cenu vyššej spotreby batérie.</string>
<string name="wake_battery">Nechať bežať na pozadí</string>
<string name="wake_battery_line">Niektoré telefóny (Samsung, Xiaomi, Huawei, OnePlus a ďalšie) kvôli batérii zastavujú aplikácie na pozadí, a s nimi aj budiace slovo. Tu vyjmite LLeMbas z optimalizácie batérie; dontkillmyapp.com vysvetľuje nastavenia vášho telefónu.</string>
<string name="wake_word_privacy">Pred vyslovením slova nič neopustí telefón. Zvuk z mikrofónu ide len do modulu pre budiace slovo v telefóne a neukladá sa; počas celého počúvania je viditeľné oznámenie. Frázy sú anglické; modul je sherpa-onnx (open source).</string>
<string name="wake_word_cost">Stojí to batériu: mikrofón zostáva zapnutý a procesor telefónu kontroluje každý okamih zvuku, bez úsporného čipu, ktorý používa vstavaný asistent. Pozastaví sa v úspornom režime, keď je asistent otvorený, a ak to nezmeníte, aj pri zhasnutej obrazovke. Po reštarte ho znova spustíte ťuknutím na oznámenie.</string>
<string name="wake_listening_for">Počúvam frázu „%1$s“</string>
<string name="wake_notification_line">Kým ju nepoviete, nič neopustí telefón.</string>
<string name="wake_paused_screen">Budiace slovo pozastavené: obrazovka je zhasnutá</string>
<string name="wake_paused_battery">Budiace slovo pozastavené: je zapnutý úsporný režim</string>
<string name="wake_paused_assistant">Budiace slovo je pozastavené, kým je asistent otvorený</string>
<string name="wake_paused_microphone">Budiace slovo pozastavené: mikrofón alebo modul nie je k dispozícii</string>
<string name="wake_stop">Prestať počúvať</string>
<string name="wake_heard">Počul som vás. Ťuknite a pýtajte sa.</string>
<string name="wake_resume">Znova počúvať budiace slovo</string>
<string name="wake_resume_line">Telefón sa reštartoval. Ťuknutím znova spustíte počúvanie.</string>
<string name="assist_notifications">Zhrnúť moje oznámenia</string>
<string name="assist_notifications_prompt">Zhrň moje oznámenia: čo potrebuje moju pozornosť?</string>
<string name="assist_notifications_phrases">moje oznámenia|mojich oznámení|moje notifikácie</string>
<string name="notification_summaries">Zhrnutia oznámení</string>
<string name="notification_summaries_switch">Dovoliť asistentovi čítať moje oznámenia, keď o to požiadam</string>
<string name="notification_summaries_line">Povedzte „zhrň moje oznámenia“, alebo ťuknite na tlačidlo v asistentovi.</string>
<string name="notification_access">Prístup k oznámeniam</string>
<string name="notification_access_on">Udelený. Prepínač Androidu je v systémových nastaveniach.</string>
<string name="notification_access_off">Zatiaľ neudelený. Ťuknutím otvoríte prepínač Androidu pre LLeMbas.</string>
<string name="notification_summaries_privacy">Predvolene vypnuté. Keď požiadate, text oznámení, ktoré sú v telefóne práve teraz (aplikácia, názov, text), pôjde s touto jedinou otázkou na vašu inštanciu a jej model. Predtým sa nič nečíta, aplikácia si nič neponechá a pri zamknutom telefóne sa nečíta nič. Prístup k oznámeniam v Androide dovolí aplikácii vidieť každé oznámenie, preto je na vás, či ho dáte a znova vezmete.</string>
<string name="nav_app">Navigačná aplikácia</string>
<string name="nav_app_auto">Tá, ktorá je nainštalovaná</string>
<string name="nav_app_google">Mapy Google</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Zakaždým sa opýtať</string>
<string name="nav_app_not_installed">Nie je nainštalovaná</string>
<string name="osmand_info">Pýtať sa OsmAnd na trasu</string>
<string name="osmand_info_line">Umožní „pridať zastávku“ a hľadanie v okolí aj pri trase nastavenej priamo v OsmAnd: LLeMbas sa OsmAnd opýta, kde ste a kam trasa vedie. Najprv LLeMbas povoľte v OsmAnd (pripojené aplikácie, s polohou); OsmAnd dá vedieť, ak povolené nie je.</string>
<string name="phone_actions_line">Model môže ponúknuť, že v telefóne niečo urobí — nastaví budík, pridá udalosť, pripraví správu, spustí trasu. Nič sa nestane, kým neťuknete na Urobiť na jeho karte, a nikdy pri zamknutom telefóne. Mapy Google spustia trasu s niekoľkými zastávkami, ale do bežiacej trasy zastávku nepridajú ani sa nedajú zastaviť; OsmAnd to vie.</string>
<string name="action_card_title">Urobiť to v telefóne?</string>
<string name="action_do">Urobiť</string>
<string name="action_running">Robím to…</string>
<string name="action_unlock">Najprv odomknite telefón, potom ťuknite na Urobiť.</string>
<string name="action_failed">Nepodarilo sa: %1$s</string>
<string name="nav_app_pick">V ktorej mapovej aplikácii?</string>
<string name="action_google_add_stop">Mapy Google nepridajú zastávku do bežiacej trasy: spustia trasu znova, cez zastávku.</string>
<string name="action_google_no_stop">Mapy Google sa nedajú zastaviť zvonka: trasu ukončite v nich.</string>
<string name="action_line_clock">Nastaví to aplikácia Hodiny.</string>
<string name="action_line_calendar">Otvorí sa kalendár s vyplnenou udalosťou; uložíte ju vy.</string>
<string name="action_line_draft">Otvorí koncept; odošlete ho sami.</string>
<string name="action_line_dial">Otvorí sa vytáčanie s číslom; hovor začnete vy.</string>
<string name="action_line_map">Trasu prevezme %1$s.</string>
<string name="action_line_now">Stane sa hneď.</string>
<string name="action_line_settings">Otvorí nastavenie; zmeníte ho vy.</string>
<string name="action_line_automation">Spustí vašu automatizáciu (Tasker, ak nie je uvedená iná aplikácia).</string>
<string name="action_line_open">Otvorí to.</string>
<string name="assist_recogniser_failed">Rozpoznávanie reči v telefóne sa zastavilo. Skúste to znova alebo zvoľte LLeMbas v Nastaveniach › Hlasový vstup.</string>
<string name="assistant_listens">Začať počúvať, keď sa asistent otvorí</string>
<string name="voice_input">Hlasový vstup</string>
@@ -401,4 +464,9 @@
<string name="voice_input_hint">Používa ho asistent aj mikrofón v konverzácii. S LLeMbas asistent ukazuje slová s malým oneskorením a pauza ich odošle, konverzácia ich zapíše, keď prestanete; s rozpoznávaním v telefóne sa objavujú, ako hovoríte.</string>
<string name="share_sending">Odosiela sa do LLeMbas…</string>
<string name="share_default_prompt">Pozrite sa na toto.</string>
<string name="share_ask_hint">Čo s tým má LLeMbas urobiť? (nepovinné)</string>
<string name="widget_hint">Opýtajte sa na čokoľvek</string>
<string name="widget_speak">Hovoriť</string>
<string name="widget_description">Pýtajte sa hlasom alebo textom, alebo pokračujte v poslednej konverzácii s asistentom. Neukazuje nič z vášho účtu.</string>
<string name="shortcut_last">Posledný chat</string>
</resources>
+69 -1
View File
@@ -379,7 +379,6 @@
<string name="assist_quick_explain_prompt">Explain what is on my screen.</string>
<string name="assist_continue">Continue the last chat</string>
<string name="assist_help">Hold the power button to open the assistant over any app, or use the Quick Settings tile.</string>
<string name="assist_no_wake_word">There is no wake word: on stock Android, listening for one is kept for the assistant built into the phone.</string>
<string name="assist_connecting">Connecting…</string>
<string name="assist_offline">%1$s cannot be reached</string>
<string name="assist_no_model">No model</string>
@@ -392,6 +391,70 @@
<string name="assist_say_it">Say it, then pause</string>
<string name="assist_type">Type instead</string>
<string name="assist_writing_down">Writing down what you said…</string>
<string name="assist_conversation">In conversation</string>
<string name="assist_conversation_line">I listen again after each answer. Say “stop” to end.</string>
<string name="assist_conversation_end">End</string>
<string name="assist_stop_words">stop|that\'s all|that is all|that\'s it|goodbye|bye|enough|end|thank you that\'s all|cancel</string>
<string name="assistant_conversation">Keep a spoken conversation going</string>
<string name="assistant_conversation_line">After a spoken answer is read aloud, the assistant listens again — until you say “stop”, tap End, or say nothing for a few seconds. Works with a headset.</string>
<string name="assist_wake_word_hint">No wake word unless you want one: Settings › Assistant › Wake word turns on LLeMbas\'s own, on this phone.</string>
<string name="channel_wake">Wake word</string>
<string name="wake_word">Wake word</string>
<string name="wake_word_listen">Listen for a wake word</string>
<string name="wake_word_line">Off by default. Say the phrase and the assistant opens, listening, over whatever app is on screen.</string>
<string name="wake_word_unavailable">Not in this build. The F-Droid build has no wake-word engine, because F-Droid builds every library from source; the build from llembas.eu has one.</string>
<string name="wake_screen_only">Only while the screen is on</string>
<string name="wake_screen_only_line">Off: it listens with the screen off too, at more cost to the battery.</string>
<string name="wake_battery">Let it run in the background</string>
<string name="wake_battery_line">Some phones (Samsung, Xiaomi, Huawei, OnePlus and others) stop background apps to save battery, and the wake word with them. Exempt LLeMbas from battery optimisation here; dontkillmyapp.com explains your phone\'s own settings.</string>
<string name="wake_word_privacy">Nothing leaves the phone before the word. The microphone\'s sound goes only to the wake-word engine on the phone and is not kept, and the notification stays up the whole time it listens. The phrases are English; the engine is sherpa-onnx (open source).</string>
<string name="wake_word_cost">It costs battery: the microphone stays on and the phone\'s processor checks every moment of sound, without the low-power chip the built-in assistant uses. It pauses in battery saver, while the assistant is open and, unless you change it, with the screen off. After a restart, tap its notification to start it again.</string>
<string name="wake_listening_for">Listening for “%1$s”</string>
<string name="wake_notification_line">Nothing leaves the phone until you say it.</string>
<string name="wake_paused_screen">Wake word paused: the screen is off</string>
<string name="wake_paused_battery">Wake word paused: battery saver is on</string>
<string name="wake_paused_assistant">Wake word paused while the assistant is open</string>
<string name="wake_paused_microphone">Wake word paused: the microphone or the engine is not available</string>
<string name="wake_stop">Stop listening</string>
<string name="wake_heard">Heard you. Tap to ask.</string>
<string name="wake_resume">Listen for the wake word again</string>
<string name="wake_resume_line">The phone restarted. Tap to start listening again.</string>
<string name="assist_notifications">Summarise my notifications</string>
<string name="assist_notifications_prompt">Summarise my notifications: what needs my attention?</string>
<string name="assist_notifications_phrases">my notifications|notifications on my phone</string>
<string name="notification_summaries">Notification summaries</string>
<string name="notification_summaries_switch">Let the assistant read my notifications when I ask</string>
<string name="notification_summaries_line">Ask “summarise my notifications”, or tap the chip in the assistant.</string>
<string name="notification_access">Notification access</string>
<string name="notification_access_on">Given. Android\'s switch for it is in the system\'s settings.</string>
<string name="notification_access_off">Not given yet. Tap to open Android\'s switch for LLeMbas.</string>
<string name="notification_summaries_privacy">Off by default. When you ask, the text of the notifications on your phone right now (app, title, text) goes with that one question to your instance and its model. Nothing is read before you ask, the app keeps none of it, and none is read while the phone is locked. Android\'s notification access lets an app see every notification, so it is yours to give and to take back.</string>
<string name="nav_app">Navigation app</string>
<string name="nav_app_auto">Whichever is installed</string>
<string name="nav_app_google">Google Maps</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Ask each time</string>
<string name="nav_app_not_installed">Not installed</string>
<string name="osmand_info">Ask OsmAnd about the route</string>
<string name="osmand_info_line">Lets “add a stop” and searches near you work with a route you set up in OsmAnd itself: LLeMbas asks OsmAnd where you are and where the route goes. Allow LLeMbas in OsmAnd first (its connected apps, with Location); OsmAnd tells you if it is not allowed.</string>
<string name="phone_actions_line">A model may offer to do things on this phone — set an alarm, add an event, draft a message, start a route. Nothing happens until you tap Do it on its card, and never while the phone is locked. Google Maps starts a route with a few stops but cannot add one to a route already running or be told to stop; OsmAnd can.</string>
<string name="action_card_title">Do this on your phone?</string>
<string name="action_do">Do it</string>
<string name="action_running">Doing it…</string>
<string name="action_unlock">Unlock the phone first, then tap Do it.</string>
<string name="action_failed">It did not work: %1$s</string>
<string name="nav_app_pick">With which map app?</string>
<string name="action_google_add_stop">Google Maps cannot add a stop to a running route: it starts the route again, through the stop.</string>
<string name="action_google_no_stop">Google Maps cannot be told to stop: end the route there.</string>
<string name="action_line_clock">The clock app sets it.</string>
<string name="action_line_calendar">The calendar opens with the event filled in; you save it.</string>
<string name="action_line_draft">Opens a draft; you send it yourself.</string>
<string name="action_line_dial">The dialler opens with the number; you place the call.</string>
<string name="action_line_map">%1$s takes the route.</string>
<string name="action_line_now">Happens at once.</string>
<string name="action_line_settings">Opens the setting; you change it.</string>
<string name="action_line_automation">Runs your automation (Tasker unless another app is named).</string>
<string name="action_line_open">Opens it.</string>
<string name="assist_recogniser_failed">The phone\'s speech recogniser stopped. Try again, or choose LLeMbas under Settings › Voice input.</string>
<string name="assistant_listens">Start listening when the assistant opens</string>
<string name="voice_input">Voice input</string>
@@ -403,4 +466,9 @@
<string name="voice_input_hint">Used by the assistant and by the microphone in a chat. With LLeMbas the assistant shows the words a moment behind you and a pause sends them, and a chat writes them down when you stop; with the phone\'s recogniser they appear as you speak.</string>
<string name="share_sending">Sending to LLeMbas…</string>
<string name="share_default_prompt">Have a look at this.</string>
<string name="share_ask_hint">What should LLeMbas do with it? (optional)</string>
<string name="widget_hint">Ask anything</string>
<string name="widget_speak">Speak</string>
<string name="widget_description">Ask by voice or text, or carry on the last assistant chat. Shows nothing from your account.</string>
<string name="shortcut_last">Last chat</string>
</resources>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.10 (shire). Do not edit. -->
<resources>
<color name="token_bg">#FFF1EAD6</color>
<color name="token_surface">#FFF8F3E5</color>
<color name="token_surface_raised">#FFFCF9F0</color>
<color name="token_border">#FFCBBF9D</color>
<color name="token_ink">#FF1F2418</color>
<color name="token_ink_muted">#FF474D3B</color>
<color name="token_accent">#FF285F3C</color>
<color name="token_accent_ink">#FFF8F3E5</color>
<color name="token_accent_soft">#1A285F3C</color>
</resources>
-13
View File
@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:shortcutId="ask"
android:enabled="true"
android:icon="@mipmap/ic_launcher"
android:shortcutShortLabel="@string/tile_ask">
<intent
android:action="android.intent.action.ASSIST"
android:targetPackage="eu.llembas.android"
android:targetClass="eu.llembas.android.assist.AssistActivity" />
</shortcut>
</shortcuts>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/widget_description"
android:initialLayout="@layout/widget_ask"
android:minWidth="250dp"
android:minHeight="40dp"
android:minResizeWidth="180dp"
android:previewLayout="@layout/widget_ask"
android:resizeMode="horizontal"
android:targetCellWidth="4"
android:targetCellHeight="1"
android:updatePeriodMillis="0"
android:widgetCategory="home_screen" />
@@ -7,9 +7,13 @@ import eu.llembas.android.assist.AssistController
import eu.llembas.android.assist.AssistTurn
import eu.llembas.android.assist.Recorder
import eu.llembas.android.assist.SheetStop
import eu.llembas.android.assist.isStopPhrase
import eu.llembas.android.assist.settle
import eu.llembas.android.assist.usePhoneRecognizer
import eu.llembas.android.auth.Prefs
import eu.llembas.android.notify.Notice
import eu.llembas.android.notify.NotificationReader
import eu.llembas.android.share.shareMessage
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@@ -87,4 +91,39 @@ class AssistTest {
assertFalse(usePhoneRecognizer(Prefs.VOICE_LEMBAS, phoneHas = true, instanceStt = true))
assertTrue(usePhoneRecognizer(Prefs.VOICE_LEMBAS, phoneHas = true, instanceStt = false))
}
@Test
fun aShareSendsTheRequestBeforeWhatWasShared() {
assertEquals("Summarise it.\n\n---\n\nhttps://example.org", shareMessage(" Summarise it. ", "https://example.org\n", "Have a look."))
assertEquals("Have a look.\n\n---\n\nSome text", shareMessage("", "Some text", "Have a look."))
// Files only: the request alone, the files go as attachments.
assertEquals("Have a look.", shareMessage(" ", "", "Have a look."))
}
@Test
fun stopEndsAConversationButAQuestionAboutStoppingDoesNot() {
val phrases = "stop|that's all|goodbye".split("|")
assertTrue(isStopPhrase("Stop.", phrases))
assertTrue(isStopPhrase("OK, that’s all, thanks", phrases))
assertTrue(isStopPhrase("stop please", phrases))
assertFalse(isStopPhrase("How do I stop the kettle from whistling in the morning?", phrases))
assertFalse(isStopPhrase("", phrases))
assertTrue(isStopPhrase("Ďakujem, to je všetko", listOf("ďakujem to je všetko")))
}
@Test
fun notificationsGoAsShortBlocksAndOnlyWhenAskedFor() {
val now = 10 * 3_600_000L
val text = NotificationReader.asText(
listOf(
Notice("Mail", "Bilbo", "The party is on Thursday.", now - 5 * 60_000),
Notice("Weather", "Rain", "", now - 3 * 3_600_000),
),
now,
)
assertEquals("[Mail · 5m ago] Bilbo\nThe party is on Thursday.\n\n[Weather · 3h ago] Rain", text)
val phrases = listOf("my notifications")
assertTrue(NotificationReader.asksAbout("Anything urgent in My Notifications?", phrases))
assertFalse(NotificationReader.asksAbout("How do notifications work on Android?", phrases))
}
}
@@ -0,0 +1,85 @@
package eu.llembas.android
import eu.llembas.android.ui.TokenKind
import eu.llembas.android.ui.highlights
import eu.llembas.android.ui.tokenize
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class HighlightTest {
/** Each token as its text and kind, for reading a test at a glance. */
private fun read(text: String, language: String): List<Pair<String, TokenKind>> =
tokenize(text, language).map { text.substring(it.start, it.end) to it.kind }
@Test
fun kotlinKeywordsStringsCommentsNumbersAndTypes() {
val got = read("val x: Int = 42 // the answer\nfun f() = \"a \\\" b\"", "kotlin")
assertTrue("val" to TokenKind.Keyword in got)
assertTrue("Int" to TokenKind.Type in got)
assertTrue("42" to TokenKind.Number in got)
assertTrue("// the answer" to TokenKind.Comment in got)
assertTrue("fun" to TokenKind.Keyword in got)
// An escaped quote does not end the string.
assertTrue("\"a \\\" b\"" to TokenKind.Text in got)
}
@Test
fun aBlockCommentRunsAcrossLines() {
val text = "/* one\n two */ int x;"
val got = read(text, "c")
assertEquals("/* one\n two */" to TokenKind.Comment, got.first())
assertTrue("int" to TokenKind.Keyword in got)
}
@Test
fun pythonTripleQuotesAndHashComments() {
val got = read("def f():\n \"\"\"Doc\n string\"\"\"\n return None # nothing", "py")
assertTrue("def" to TokenKind.Keyword in got)
assertTrue("\"\"\"Doc\n string\"\"\"" to TokenKind.Text in got)
assertTrue("None" to TokenKind.Keyword in got)
assertTrue("# nothing" to TokenKind.Comment in got)
}
@Test
fun anUnclosedQuoteColoursOneLineNotTheFile() {
val got = read("echo don't\nls -la", "bash")
val string = got.first { it.second == TokenKind.Text }
assertFalse(string.first.contains('\n'))
}
@Test
fun sqlIgnoresCaseAndShellHasVariables() {
assertTrue("SELECT" to TokenKind.Keyword in read("SELECT * FROM t -- all", "sql"))
assertTrue("-- all" to TokenKind.Comment in read("SELECT * FROM t -- all", "sql"))
assertTrue("\$HOME" to TokenKind.Attribute in read("cd \$HOME", "sh"))
}
@Test
fun markupTagsAttributesAndValues() {
val got = read("<!-- note -->\n<a href=\"x\">don't</a>", "xml")
assertEquals("<!-- note -->" to TokenKind.Comment, got.first())
assertTrue("a" to TokenKind.Tag in got)
assertTrue("href" to TokenKind.Attribute in got)
assertTrue("\"x\"" to TokenKind.Text in got)
// Prose between tags is not a string.
assertFalse(got.any { it.first.startsWith("'") })
}
@Test
fun yamlKeys() {
val got = read("name: lembas\ncount: 3\n# end", "yaml")
assertTrue("name" to TokenKind.Type in got)
assertTrue("3" to TokenKind.Number in got)
assertTrue("# end" to TokenKind.Comment in got)
}
@Test
fun anUnknownLanguageIsPlain() {
assertFalse(highlights("brainfuck"))
assertTrue(tokenize("anything at all", "").isEmpty())
assertTrue(highlights("TypeScript"))
assertTrue(highlights("c++"))
}
}
@@ -0,0 +1,78 @@
package eu.llembas.android
import eu.llembas.android.actions.Args
import eu.llembas.android.actions.NavApp
import eu.llembas.android.actions.NavIntents
import eu.llembas.android.actions.PhoneActions
import eu.llembas.android.actions.Place
import eu.llembas.android.api.AskFrame
import eu.llembas.android.api.CardAnswer
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.PhoneResult
import eu.llembas.android.ui.chat.phoneFacts
import kotlinx.serialization.json.jsonObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class PhoneActionsTest {
private fun args(json: String) = Args(LembasJson.parseToJsonElement(json).jsonObject)
@Test
fun placesAreReadLeniently() {
val a = args("""{"destination": {"name": "Rivendell", "lat": "47.1", "lon": 8.5}, "stops": ["Bree", {"query": "inn"}], "hour": "7"}""")
assertEquals(Place("Rivendell", 47.1, 8.5), a.place("destination"))
assertEquals(listOf(Place(query = "Bree"), Place(query = "inn")), a.places("stops"))
assertEquals(7, a.int("hour"))
assertNull(a.place("missing"))
}
@Test
fun theNavigationAppIsTheOneInstalledOrAsked() {
val both = listOf(NavApp.GoogleMaps, NavApp.OsmAnd)
assertEquals(NavApp.OsmAnd, NavApp.chosen("", listOf(NavApp.OsmAnd)))
// Both installed and nothing chosen: the card asks.
assertNull(NavApp.chosen("", both))
assertEquals(NavApp.GoogleMaps, NavApp.chosen("google", both))
assertNull(NavApp.chosen(NavApp.PREF_ASK, both))
// Chosen but since uninstalled: the one there is.
assertEquals(NavApp.GoogleMaps, NavApp.chosen("osmand", listOf(NavApp.GoogleMaps)))
}
@Test
fun aRouteForOsmAndIsGpxWithItsPointsInOrder() {
val gpx = NavIntents.gpx(listOf(Place("Bree & Co", 1.0, 2.0), Place("Rivendell", 3.0, 4.0)))
assertTrue(gpx.contains("<rtept lat=\"1.0\" lon=\"2.0\"><name>Bree &amp; Co</name></rtept><rtept lat=\"3.0\" lon=\"4.0\">"))
}
@Test
fun clockTimesAndNumbersAreCheckedAgain() {
assertEquals(7 to 5, PhoneActions.clock("07:05"))
assertNull(PhoneActions.clock("24:00"))
assertNull(PhoneActions.clock("7 am"))
// A name the messaging app would have to find is left out: the person picks the contact.
assertEquals(listOf("+421 900 123 456"), PhoneActions.smsNumbers(listOf("+421 900 123 456", "Sam")))
assertTrue(PhoneActions.urlAllowed("HTTPS://example.org"))
assertFalse(PhoneActions.urlAllowed("javascript:alert(1)"))
assertFalse(PhoneActions.urlAllowed("https://"))
}
@Test
fun theCardSaysWhatWillHappenFromTheContract() {
val frame = requireNotNull(javaClass.classLoader!!.getResource("event_ask_phone.json")).readText()
val cards = LembasJson.decodeFromString(AskFrame.serializer(), frame).cards
assertEquals(listOf("phone_action"), cards.map { it.kind }.distinct())
val phones = cards.map { requireNotNull(it.items.single().phone) }
assertEquals("07:00 · mon tue wed thu fri · Work", phoneFacts(phones[0]))
assertEquals("Bakery (48.894, 18.044) · Home (1 Bagshot Row, Hobbiton) · drive", phoneFacts(phones[1]))
assertEquals("Bakery (Bakery, Bywater) · Home (1 Bagshot Row, Hobbiton)", phoneFacts(phones[2]))
assertEquals("", phoneFacts(phones[3]))
// The answer the server reads: {"result": {"status", "message"}}, nothing else.
assertEquals(
"""{"result":{"status":"done","message":"ok"}}""",
LembasJson.encodeToString(CardAnswer.serializer(), CardAnswer(result = PhoneResult("done", "ok"))),
)
}
}
@@ -0,0 +1,32 @@
package eu.llembas.android
import eu.llembas.android.wake.WakePause
import eu.llembas.android.wake.WakePhrases
import eu.llembas.android.wake.wakePause
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class WakeTest {
@Test
fun itListensOnlyWhenNothingStandsInTheWay() {
assertEquals(WakePause.None, wakePause(screenOn = true, screenOnly = true, batterySaver = false, sheetOpen = false, micAllowed = true))
assertEquals(WakePause.ScreenOff, wakePause(screenOn = false, screenOnly = true, batterySaver = false, sheetOpen = false, micAllowed = true))
// Told to listen with the screen off too.
assertEquals(WakePause.None, wakePause(screenOn = false, screenOnly = false, batterySaver = false, sheetOpen = false, micAllowed = true))
assertEquals(WakePause.BatterySaver, wakePause(screenOn = true, screenOnly = true, batterySaver = true, sheetOpen = false, micAllowed = true))
// The sheet has the microphone.
assertEquals(WakePause.Assistant, wakePause(screenOn = true, screenOnly = true, batterySaver = true, sheetOpen = true, micAllowed = true))
assertEquals(WakePause.NoMicrophone, wakePause(screenOn = true, screenOnly = true, batterySaver = false, sheetOpen = false, micAllowed = false))
}
@Test
fun phrasesAreSpelledInTheModelsPieces() {
assertEquals("hey_lembas", WakePhrases.byId("nonsense").id)
// Every piece of the spelling starts a word with ▁ or continues one; no spaces inside a word.
for (phrase in WakePhrases.all) {
assertTrue(phrase.tokens.startsWith("▁"))
assertEquals(phrase.words.split(' ').size, phrase.tokens.split(' ').count { it.startsWith("▁") })
}
}
}
@@ -44,6 +44,8 @@ import eu.llembas.android.assist.Connection
import eu.llembas.android.assist.LastAssist
import eu.llembas.android.auth.Instance
import eu.llembas.android.auth.Prefs
import eu.llembas.android.share.ShareState
import eu.llembas.android.share.SharedFile
import eu.llembas.android.ui.chat.ChatState
import eu.llembas.android.ui.chat.Draft
import eu.llembas.android.ui.home.ChatsState
@@ -355,11 +357,13 @@ object Fakes {
val settings = SettingsState(
instances = listOf(home, work),
active = home,
prefs = Prefs(theme = "", assistantTemporary = true, accountLanguage = "en"),
prefs = Prefs(theme = "", assistantTemporary = true, accountLanguage = "en", notificationSummaries = true),
hasDistributor = true,
version = "1.0.0-beta.3",
selfUpdate = true,
phoneRecognizer = true,
wakeAvailable = true,
navApps = listOf("google", "osmand"),
)
// The assistant's sheet, as it opens and as it answers.
@@ -381,7 +385,7 @@ object Fakes {
)
/** Opened from the tile, nothing asked yet: the last chat, the help, the microphone. */
val assistOpened = assistBase.copy(last = LastAssist("c1", "Packing for the road", 0), screenText = true, includeScreen = true)
val assistOpened = assistBase.copy(last = LastAssist("c1", "Packing for the road", 0), screenText = true, includeScreen = true, canReadNotifications = true)
/** A spoken question answered, the answer read aloud. */
val assistAnswered = assistBase.copy(
@@ -390,6 +394,16 @@ object Fakes {
speaking = true,
)
/** A spoken conversation: the answer read, listening again. */
val assistConversation = assistBase.copy(
chatId = "c9",
turns = listOf(AssistTurn(question.text.orEmpty(), earlier = answer.steps)),
conversation = true,
listening = true,
heard = "And how long for the honey cakes",
level = 0.3f,
)
/** An answer being written. */
val assistWriting = assistBase.copy(
chatId = "c9",
@@ -411,6 +425,72 @@ object Fakes {
error = "Home cannot be reached.",
)
/** Source files for the viewer's highlighting: language and text. */
val codeFiles: Map<String, Pair<String, String>> = mapOf(
"kotlin" to (
"kotlin" to """
|package shire.kitchen
|
|/** Waybread keeps for days if it is wrapped in a leaf. */
|data class Lembas(val pieces: Int = 3, val wrapped: Boolean = true)
|
|fun share(bread: Lembas, walkers: List<String>): Map<String, Double> {
| if (!bread.wrapped) return emptyMap() // it has gone stale
| val each = bread.pieces.toDouble() / walkers.size
| return walkers.associateWith { each * 0.5 }
|}
""".trimMargin()
),
"python" to (
"python" to """
|import json
|
|
|class Pantry:
| ""${'"'}What is left for the road.""${'"'}
|
| def __init__(self, path: str) -> None:
| self.items = json.load(open(path)) # one file, read once
|
| def count(self, name="lembas"):
| return sum(1 for item in self.items if item == name) or None
""".trimMargin()
),
"yaml" to (
"yaml" to """
|# The road east
|name: Long Road
|stops: 7
|provisions:
| - lembas
| - "honey cakes"
|rest: true
""".trimMargin()
),
"typescript" to (
"typescript" to """
|interface Stop { name: string; miles: number }
|
|export async function next(stops: Stop[]): Promise<Stop | undefined> {
| // the nearest first
| return stops.sort((a, b) => a.miles - b.miles)[0];
|}
""".trimMargin()
),
)
// A share from another app.
val shareLink = ShareState(
text = "The Long Road: a walker's guide to waybread\nhttps://example.org/waybread",
last = LastAssist("c1", "Packing for the road", 0),
)
val shareFiles = ShareState(
files = listOf(SharedFile("map-of-the-road.jpg", image = true), SharedFile("provisions.pdf", image = false)),
last = LastAssist("c1", "Packing for the road", 0),
error = "Home cannot be reached.",
)
// Scheduled: shaped as the server's contract fixtures are (contract/schedule*.json).
private fun rule(text: String) = LembasJson.parseToJsonElement(text).jsonObject
@@ -1,10 +1,14 @@
@file:OptIn(ExperimentalRoborazziApi::class)
package eu.llembas.android.shots
import android.view.LayoutInflater
import androidx.compose.foundation.background
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.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -16,16 +20,30 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.github.takahirom.roborazzi.ExperimentalRoborazziApi
import com.github.takahirom.roborazzi.RoborazziComposeOptions
import com.github.takahirom.roborazzi.captureRoboImage
import com.github.takahirom.roborazzi.inspectionMode
import com.github.takahirom.roborazzi.size
import eu.llembas.android.R
import eu.llembas.android.actions.NavApp
import eu.llembas.android.assist.AssistActions
import eu.llembas.android.assist.AssistSheetContent
import eu.llembas.android.assist.AssistSheetFrame
import eu.llembas.android.assist.AssistUiState
import eu.llembas.android.share.ShareActions
import eu.llembas.android.share.ShareSheetContent
import eu.llembas.android.share.ShareState
import eu.llembas.android.ui.chat.ActivityActions
import eu.llembas.android.ui.chat.ActivityContent
import eu.llembas.android.ui.chat.CardSheet
import eu.llembas.android.ui.chat.ChatActions
import eu.llembas.android.ui.chat.ChatContent
import eu.llembas.android.ui.chat.CodeBlock
import eu.llembas.android.ui.chat.ModelPickerContent
import eu.llembas.android.ui.chat.PhoneCardContent
import eu.llembas.android.ui.chat.PhoneCardState
import eu.llembas.android.ui.chat.TuneContent
import eu.llembas.android.ui.chat.modelId
import eu.llembas.android.ui.home.ArchivedActions
@@ -45,6 +63,7 @@ import eu.llembas.android.ui.settings.LanguageChoices
import eu.llembas.android.ui.settings.SettingsActions
import eu.llembas.android.ui.settings.SettingsContent
import eu.llembas.android.ui.theme.LocalPalette
import eu.llembas.android.ui.viewer.FileBody
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@@ -66,6 +85,8 @@ private object NoSettingsActions : SettingsActions
private object NoAssistActions : AssistActions
private object NoShareActions : ShareActions
/**
* The app's screens with made-up data ([Fakes]), as a phone shows them: each in Shire and
* Moria, at a large phone's size and, where things crowd, a small one's and with large type.
@@ -244,6 +265,8 @@ class ScreenShots {
shoot("21-assistant-writing", content = over(Fakes.assistWriting, false))
shoot("22-assistant-locked", content = over(Fakes.assistOpened, true))
shoot("23-assistant-offline", Phone.Small, content = over(Fakes.assistOffline, false))
shoot("24-assistant-conversation", content = over(Fakes.assistConversation, false))
shoot("24-assistant-conversation", Phone.Small, fontScale = 1.5f, content = over(Fakes.assistConversation, false))
}
/**
@@ -287,6 +310,82 @@ class ScreenShots {
shoot("28-memory", Phone.Small, fontScale = 1.5f) { MemoryContent(Fakes.memory, NoMemoryActions) }
shoot("28-memory-none") { MemoryContent(MemoryState(), NoMemoryActions) }
}
/** The file viewer's code in the theme's colours, a few languages, and a reply's code block. */
@Test
fun highlighting() {
for ((name, file) in Fakes.codeFiles) {
shoot("33-viewer-$name") { FileBody("code", file.first, line = 3, text = file.second) }
}
shoot("33-viewer-kotlin", Phone.Small, fontScale = 1.5f) { FileBody("code", "kotlin", line = 0, text = Fakes.codeFiles.getValue("kotlin").second) }
shoot("34-code-block") {
Column(Modifier.fillMaxSize().padding(16.dp)) { CodeBlock("ts", Fakes.codeFiles.getValue("typescript").second) }
}
}
/**
* The phone_action cards as the server's contract has them (`event_ask_phone.json`): an
* alarm, a route through a stop with both map apps to choose from, a stop added in Google
* Maps (its limit said), and the phone still locked.
*/
@Test
fun phoneActions() {
val frame = requireNotNull(javaClass.classLoader!!.getResource("event_ask_phone.json")).readText()
val phones = eu.llembas.android.api.LembasJson.decodeFromString(eu.llembas.android.api.AskFrame.serializer(), frame).cards
.map { requireNotNull(it.items.single().phone) }
val both = listOf(NavApp.GoogleMaps, NavApp.OsmAnd)
val card: (Int, NavApp?, PhoneCardState) -> @Composable () -> Unit = { i, chosen, state ->
{ Column(Modifier.fillMaxSize().padding(16.dp)) { PhoneCardContent(phones[i], both, chosen, state) } }
}
shoot("35-phone-alarm", content = card(0, null, PhoneCardState()))
shoot("35-phone-alarm", Phone.Small, fontScale = 1.5f, content = card(0, null, PhoneCardState()))
shoot("36-phone-navigate-pick", content = card(1, null, PhoneCardState()))
shoot("37-phone-add-stop-google", content = card(2, NavApp.GoogleMaps, PhoneCardState()))
shoot("38-phone-stop-locked", content = card(3, NavApp.OsmAnd, PhoneCardState(locked = true)))
}
/** "Ask LLeMbas" from another app's share menu: a link, and a picture with a file. */
@Test
fun share() {
val over: (ShareState) -> @Composable () -> Unit = { state ->
{
Box(Modifier.fillMaxSize()) {
ChatContent(Fakes.transcript, NoChatActions, agent = false)
AssistSheetFrame(onDismiss = {}) { handle, _ -> ShareSheetContent(state, NoShareActions, handle) }
}
}
}
shoot("30-share-link", content = over(Fakes.shareLink))
shoot("30-share-link", Phone.Small, fontScale = 1.5f, content = over(Fakes.shareLink))
shoot("31-share-files", content = over(Fakes.shareFiles))
}
/** The home-screen widget, as the launcher inflates it (light; [widgetNight] is dark). */
@Test
fun widget() = shootWidget("light")
@Test
@Config(qualifiers = "+night")
fun widgetNight() = shootWidget("dark")
private fun shootWidget(theme: String) {
for (phone in listOf(Phone.Large, Phone.Small)) {
captureRoboImage(
filePath = "build/screenshots/${phone.tag}-32-widget-$theme.png",
roborazziComposeOptions = RoborazziComposeOptions {
size(phone.widthDp, 120)
inspectionMode(true)
},
) {
Box(Modifier.fillMaxSize().padding(16.dp), contentAlignment = Alignment.Center) {
AndroidView(
factory = { context -> LayoutInflater.from(context).inflate(R.layout.widget_ask, null) },
modifier = Modifier.fillMaxWidth().height(64.dp),
)
}
}
}
}
}
/**
+162
View File
@@ -0,0 +1,162 @@
{
"cards": [
{
"id": "card5",
"kind": "phone_action",
"why": "",
"dismissable": true,
"expires_in": null,
"items": [
{
"index": 0,
"key": "phone",
"kind": "phone_action",
"tool": "phone_action",
"title": "Alarm at 07:00 on weekdays",
"header": "",
"detail": "alarm",
"reason": "",
"purpose": "",
"options": [],
"multiple": false,
"free_text": false,
"editable": false,
"plan": null,
"mode_choice": false,
"job": "",
"subagent": null,
"phone": {
"action": "alarm",
"summary": "Alarm at 07:00 on weekdays",
"time": "07:00",
"days": [
"mon",
"tue",
"wed",
"thu",
"fri"
],
"label": "Work"
}
}
]
},
{
"id": "card6",
"kind": "phone_action",
"why": "",
"dismissable": true,
"expires_in": null,
"items": [
{
"index": 0,
"key": "phone",
"kind": "phone_action",
"tool": "phone_action",
"title": "Drive home via the bakery",
"header": "",
"detail": "navigate",
"reason": "",
"purpose": "",
"options": [],
"multiple": false,
"free_text": false,
"editable": false,
"plan": null,
"mode_choice": false,
"job": "",
"subagent": null,
"phone": {
"action": "navigate",
"summary": "Drive home via the bakery",
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
},
"stops": [
{
"name": "Bakery",
"lat": 48.894,
"lon": 18.044
}
],
"mode": "drive",
"replace_route": false
}
}
]
},
{
"id": "card7",
"kind": "phone_action",
"why": "",
"dismissable": true,
"expires_in": null,
"items": [
{
"index": 0,
"key": "phone",
"kind": "phone_action",
"tool": "phone_action",
"title": "Add the bakery to the route",
"header": "",
"detail": "add_stop",
"reason": "",
"purpose": "",
"options": [],
"multiple": false,
"free_text": false,
"editable": false,
"plan": null,
"mode_choice": false,
"job": "",
"subagent": null,
"phone": {
"action": "add_stop",
"summary": "Add the bakery to the route",
"stop": {
"name": "Bakery",
"query": "Bakery, Bywater"
},
"destination": {
"name": "Home",
"query": "1 Bagshot Row, Hobbiton"
}
}
}
]
},
{
"id": "card8",
"kind": "phone_action",
"why": "",
"dismissable": true,
"expires_in": null,
"items": [
{
"index": 0,
"key": "phone",
"kind": "phone_action",
"tool": "phone_action",
"title": "End the route",
"header": "",
"detail": "stop_navigation",
"reason": "",
"purpose": "",
"options": [],
"multiple": false,
"free_text": false,
"editable": false,
"plan": null,
"mode_choice": false,
"job": "",
"subagent": null,
"phone": {
"action": "stop_navigation",
"summary": "End the route"
}
}
]
}
]
}
+3 -3
View File
@@ -1,5 +1,5 @@
{
"ref": "v2.0.0-beta.9",
"commit": "3b7da5fc7ac72d5de9229919793dd299c03da6a8",
"sha256": "08565486a9707bf7f11a7e5baeae16fbae38598d89975c5ad6c8178cd066a6c5"
"ref": "v2.0.0-beta.10",
"commit": "6d1ab36371c8492ee2590fbe25d112d73513a9ae",
"sha256": "d82cfc3a93ec70127c6bdff1a1b0f564d4276428ffc6ffb7a66cf13bfe746acd"
}
+46 -3
View File
@@ -2,14 +2,19 @@
"""The server's colours, as the app's Compose theme.
scripts/fetch-tokens.py <server-ref> read tokens.css at that ref (a tag such as v1.7.0),
write Tokens.kt and tokens.lock.json
scripts/fetch-tokens.py verify: Tokens.kt matches tokens.lock.json
write Tokens.kt, the colour resources and tokens.lock.json
scripts/fetch-tokens.py verify: they match tokens.lock.json
The server is a git checkout, LLeMbas beside this repository by default (LEMBAS_SERVER names
another). Only the colour tokens of the two themes are read -- `moria` (declared on `:root`) and
`shire` -- and each becomes a `Palette` in Kotlin. The lock records the ref, the commit and the
SHA-256 of the generated file, as LLeMbas Desktop's `tokens.lock.json` does: the file in the tree
says which server version the look comes from, and CI refuses a copy that drifted.
What Compose cannot draw -- the home-screen widget, the shortcuts' icons -- takes the same colours
as Android resources: `values/tokens.xml` from `shire` and `values-night/tokens.xml` from `moria`,
a few of the tokens as `@color/token_<name>`, so a widget follows the phone's dark mode in the
app's own colours.
"""
from __future__ import annotations
@@ -27,6 +32,10 @@ SERVER = Path(os.environ.get("LEMBAS_SERVER", ROOT.parent / "LLeMbas"))
SOURCE = "src/lembas/web/static/css/tokens.css"
OUT = ROOT / "app/src/main/java/eu/llembas/android/ui/theme/Tokens.kt"
LOCK = ROOT / "tokens.lock.json"
RES = ROOT / "app/src/main/res"
# The tokens a resource reads, and which theme each folder takes.
RES_NAMES = ("bg", "surface", "surface-raised", "border", "ink", "ink-muted", "accent", "accent-ink", "accent-soft")
RES_THEMES = {"values": "shire", "values-night": "moria"}
# The tokens the app uses, in the order they are written. A token missing from a theme is an
# error rather than a default: a palette that silently fell back would look right and be wrong.
@@ -75,6 +84,32 @@ def camel(name: str) -> str:
return head + "".join(p.capitalize() for p in rest)
def android_colour(value: str) -> str:
"""#AARRGGBB, as a resource writes it."""
return "#" + argb(value)[2:]
def theme_values(css: str, theme: str) -> dict[str, str]:
return dict(re.findall(r"--([a-z0-9-]+)\s*:\s*([^;]+);", block(css, THEMES[theme])))
def generate_res(css: str, ref: str, theme: str) -> str:
values = theme_values(css, theme)
lines = [
'<?xml version="1.0" encoding="utf-8"?>',
f"<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at {ref} ({theme}). Do not edit. -->",
"<resources>",
*[f' <color name="token_{n.replace("-", "_")}">{android_colour(values[n])}</color>' for n in RES_NAMES],
"</resources>",
"",
]
return "\n".join(lines)
def res_files() -> dict[str, Path]:
return {folder: RES / folder / "tokens.xml" for folder in RES_THEMES}
def generate(css: str, ref: str) -> str:
lines = [
"// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at "
@@ -105,6 +140,9 @@ def main() -> None:
lock = json.loads(LOCK.read_text())
if sha(OUT) != lock["sha256"]:
sys.exit(f"fetch-tokens: {OUT.name} does not match {LOCK.name} (server {lock['tag']})")
for folder, path in res_files().items():
if not path.exists() or sha(path) != lock.get("res", {}).get(folder):
sys.exit(f"fetch-tokens: {folder}/tokens.xml does not match {LOCK.name} (server {lock['tag']})")
print(f"fetch-tokens: {OUT.name} matches {LOCK.name} (server {lock['tag']})")
return
ref = sys.argv[1]
@@ -118,8 +156,13 @@ def main() -> None:
).stdout
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(generate(css, ref), encoding="utf-8")
res = {}
for folder, path in res_files().items():
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(generate_res(css, ref, RES_THEMES[folder]), encoding="utf-8")
res[folder] = sha(path)
LOCK.write_text(
json.dumps({"tag": ref, "commit": commit, "sha256": sha(OUT)}, indent=2) + "\n"
json.dumps({"tag": ref, "commit": commit, "sha256": sha(OUT), "res": res}, indent=2) + "\n"
)
print(f"fetch-tokens: wrote {OUT.relative_to(ROOT)} from {ref} ({commit[:12]})")
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""The wake-word engine and its model, for the `full` build -- fetched, never committed.
scripts/fetch-wakeword.py download (or check) both, hash-pinned
The engine is sherpa-onnx (Apache-2.0, k2-fsa): its Android library, as the project publishes it
on its GitHub releases (onnxruntime inside, MIT). The model is its English keyword spotter,
`sherpa-onnx-kws-zipformer-gigaspeech-3.3M-2024-01-01` (Apache-2.0, trained with icefall), of
which the int8 encoder, decoder and joiner and the token table go into the APK's assets.
Neither file is in the repository: prebuilt binaries are not source. CI runs this before Gradle;
an F-Droid build, which builds every library from source, uses the `fdroid` flavour, which has
no engine (`app/src/fdroid/.../wake/Engine.kt`). Every download is checked against the SHA-256
below before anything is written where the build reads it.
"""
from __future__ import annotations
import hashlib
import io
import sys
import tarfile
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
VERSION = "2.0.1"
AAR_URL = f"https://github.com/k2-fsa/sherpa-onnx/releases/download/v{VERSION}/sherpa-onnx-{VERSION}.aar"
AAR_SHA = "a8d09d1d32f3eb8520482c6d3d43fae674681c5b050385967c70a3c2c9bf0ee7"
AAR = ROOT / "app/libs" / f"sherpa-onnx-{VERSION}.aar"
MODEL = "sherpa-onnx-kws-zipformer-gigaspeech-3.3M-2024-01-01"
MODEL_URL = f"https://github.com/k2-fsa/sherpa-onnx/releases/download/kws-models/{MODEL}.tar.bz2"
MODEL_SHA = "f170013b4716e41b62b9bfd809687c207cef798ef9bc6534d524e17af9b6561a"
ASSETS = ROOT / "app/src/full/assets/wakeword"
# The file in the archive -> its name in the assets, and its SHA-256.
FILES = {
"encoder-epoch-12-avg-2-chunk-16-left-64.int8.onnx": ("encoder.int8.onnx", "1e721676515bcd42a186979733981213c66c80db680e1cc582dfedf3be76e678"),
"decoder-epoch-12-avg-2-chunk-16-left-64.int8.onnx": ("decoder.int8.onnx", "e40ff43297abe815e8898494c17e71bba2152d9d40fa3eb803f75d0f7533329a"),
"joiner-epoch-12-avg-2-chunk-16-left-64.int8.onnx": ("joiner.int8.onnx", "eae9da0c7e1e6c6a3f4cc42d167899c388f6c6701b94cb96320e4f55df79624c"),
"tokens.txt": ("tokens.txt", "fd2ded4050a55d2b1578870ba8697d02371980217806b7558bd0a5cc60f3ba53"),
}
def sha(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def download(url: str, expected: str) -> bytes:
for attempt in range(5):
try:
with urllib.request.urlopen(url, timeout=120) as response:
data = response.read()
break
except OSError as e: # GitHub's release assets answer 5xx for minutes at a time
if attempt == 4:
sys.exit(f"fetch-wakeword: {url}: {e}")
if sha(data) != expected:
sys.exit(f"fetch-wakeword: {url} is not the pinned file (sha256 {sha(data)})")
return data
def main() -> None:
if not (AAR.exists() and sha(AAR.read_bytes()) == AAR_SHA):
AAR.parent.mkdir(parents=True, exist_ok=True)
AAR.write_bytes(download(AAR_URL, AAR_SHA))
print(f"fetch-wakeword: {AAR.relative_to(ROOT)}")
wanted = {ASSETS / name: digest for name, digest in FILES.values()}
if all(p.exists() and sha(p.read_bytes()) == d for p, d in wanted.items()):
print("fetch-wakeword: engine and model are in place")
return
archive = tarfile.open(fileobj=io.BytesIO(download(MODEL_URL, MODEL_SHA)), mode="r:bz2")
ASSETS.mkdir(parents=True, exist_ok=True)
for source, (name, digest) in FILES.items():
data = archive.extractfile(f"{MODEL}/{source}").read()
if sha(data) != digest:
sys.exit(f"fetch-wakeword: {source} in the archive is not the pinned file")
(ASSETS / name).write_bytes(data)
print(f"fetch-wakeword: {ASSETS.relative_to(ROOT)} ({len(FILES)} files)")
if __name__ == "__main__":
main()
+69 -1
View File
@@ -404,7 +404,6 @@ STRINGS: dict[str, str] = {
"assist_quick_explain_prompt": "Explain what is on my screen.",
"assist_continue": "Continue the last chat",
"assist_help": "Hold the power button to open the assistant over any app, or use the Quick Settings tile.",
"assist_no_wake_word": "There is no wake word: on stock Android, listening for one is kept for the assistant built into the phone.",
"assist_connecting": "Connecting…",
"assist_offline": "%1$s cannot be reached",
"assist_no_model": "No model",
@@ -417,6 +416,70 @@ STRINGS: dict[str, str] = {
"assist_say_it": "Say it, then pause",
"assist_type": "Type instead",
"assist_writing_down": "Writing down what you said…",
"assist_conversation": "In conversation",
"assist_conversation_line": "I listen again after each answer. Say “stop” to end.",
"assist_conversation_end": "End",
"assist_stop_words": "stop|that's all|that is all|that's it|goodbye|bye|enough|end|thank you that's all|cancel",
"assistant_conversation": "Keep a spoken conversation going",
"assistant_conversation_line": "After a spoken answer is read aloud, the assistant listens again — until you say “stop”, tap End, or say nothing for a few seconds. Works with a headset.",
"assist_wake_word_hint": "No wake word unless you want one: Settings › Assistant › Wake word turns on LLeMbas's own, on this phone.",
"channel_wake": "Wake word",
"wake_word": "Wake word",
"wake_word_listen": "Listen for a wake word",
"wake_word_line": "Off by default. Say the phrase and the assistant opens, listening, over whatever app is on screen.",
"wake_word_unavailable": "Not in this build. The F-Droid build has no wake-word engine, because F-Droid builds every library from source; the build from llembas.eu has one.",
"wake_screen_only": "Only while the screen is on",
"wake_screen_only_line": "Off: it listens with the screen off too, at more cost to the battery.",
"wake_battery": "Let it run in the background",
"wake_battery_line": "Some phones (Samsung, Xiaomi, Huawei, OnePlus and others) stop background apps to save battery, and the wake word with them. Exempt LLeMbas from battery optimisation here; dontkillmyapp.com explains your phone's own settings.",
"wake_word_privacy": "Nothing leaves the phone before the word. The microphone's sound goes only to the wake-word engine on the phone and is not kept, and the notification stays up the whole time it listens. The phrases are English; the engine is sherpa-onnx (open source).",
"wake_word_cost": "It costs battery: the microphone stays on and the phone's processor checks every moment of sound, without the low-power chip the built-in assistant uses. It pauses in battery saver, while the assistant is open and, unless you change it, with the screen off. After a restart, tap its notification to start it again.",
"wake_listening_for": "Listening for “%1$s”",
"wake_notification_line": "Nothing leaves the phone until you say it.",
"wake_paused_screen": "Wake word paused: the screen is off",
"wake_paused_battery": "Wake word paused: battery saver is on",
"wake_paused_assistant": "Wake word paused while the assistant is open",
"wake_paused_microphone": "Wake word paused: the microphone or the engine is not available",
"wake_stop": "Stop listening",
"wake_heard": "Heard you. Tap to ask.",
"wake_resume": "Listen for the wake word again",
"wake_resume_line": "The phone restarted. Tap to start listening again.",
"assist_notifications": "Summarise my notifications",
"assist_notifications_prompt": "Summarise my notifications: what needs my attention?",
"assist_notifications_phrases": "my notifications|notifications on my phone",
"notification_summaries": "Notification summaries",
"notification_summaries_switch": "Let the assistant read my notifications when I ask",
"notification_summaries_line": "Ask “summarise my notifications”, or tap the chip in the assistant.",
"notification_access": "Notification access",
"notification_access_on": "Given. Android's switch for it is in the system's settings.",
"notification_access_off": "Not given yet. Tap to open Android's switch for LLeMbas.",
"notification_summaries_privacy": "Off by default. When you ask, the text of the notifications on your phone right now (app, title, text) goes with that one question to your instance and its model. Nothing is read before you ask, the app keeps none of it, and none is read while the phone is locked. Android's notification access lets an app see every notification, so it is yours to give and to take back.",
"nav_app": "Navigation app",
"nav_app_auto": "Whichever is installed",
"nav_app_google": "Google Maps",
"nav_app_osmand": "OsmAnd",
"nav_app_ask": "Ask each time",
"nav_app_not_installed": "Not installed",
"osmand_info": "Ask OsmAnd about the route",
"osmand_info_line": "Lets “add a stop” and searches near you work with a route you set up in OsmAnd itself: LLeMbas asks OsmAnd where you are and where the route goes. Allow LLeMbas in OsmAnd first (its connected apps, with Location); OsmAnd tells you if it is not allowed.",
"phone_actions_line": "A model may offer to do things on this phone — set an alarm, add an event, draft a message, start a route. Nothing happens until you tap Do it on its card, and never while the phone is locked. Google Maps starts a route with a few stops but cannot add one to a route already running or be told to stop; OsmAnd can.",
"action_card_title": "Do this on your phone?",
"action_do": "Do it",
"action_running": "Doing it…",
"action_unlock": "Unlock the phone first, then tap Do it.",
"action_failed": "It did not work: %1$s",
"nav_app_pick": "With which map app?",
"action_google_add_stop": "Google Maps cannot add a stop to a running route: it starts the route again, through the stop.",
"action_google_no_stop": "Google Maps cannot be told to stop: end the route there.",
"action_line_clock": "The clock app sets it.",
"action_line_calendar": "The calendar opens with the event filled in; you save it.",
"action_line_draft": "Opens a draft; you send it yourself.",
"action_line_dial": "The dialler opens with the number; you place the call.",
"action_line_map": "%1$s takes the route.",
"action_line_now": "Happens at once.",
"action_line_settings": "Opens the setting; you change it.",
"action_line_automation": "Runs your automation (Tasker unless another app is named).",
"action_line_open": "Opens it.",
"assist_recogniser_failed": "The phone's speech recogniser stopped. Try again, or choose LLeMbas under Settings › Voice input.",
"assistant_listens": "Start listening when the assistant opens",
"voice_input": "Voice input",
@@ -429,6 +492,11 @@ STRINGS: dict[str, str] = {
# Share
"share_sending": "Sending to LLeMbas…",
"share_default_prompt": "Have a look at this.",
"share_ask_hint": "What should LLeMbas do with it? (optional)",
"widget_hint": "Ask anything",
"widget_speak": "Speak",
"widget_description": "Ask by voice or text, or carry on the last assistant chat. Shows nothing from your account.",
"shortcut_last": "Last chat",
}
+560 -16
View File
File diff suppressed because it is too large. Load diff
+7 -3
View File
@@ -1,5 +1,9 @@
{
"tag": "v2.0.0-beta.9",
"commit": "3b7da5fc7ac72d5de9229919793dd299c03da6a8",
"sha256": "9057a56beb78ef9f3042555841014b9372ac415e70e054f41afcd488a9f14777"
"tag": "v2.0.0-beta.10",
"commit": "6d1ab36371c8492ee2590fbe25d112d73513a9ae",
"sha256": "eefaead797a90d3b0cb1262057a40d2eb8eab31d0d6dbbc23a387865aa76bef8",
"res": {
"values": "9b2a7fcad4b0fe02c6863f35d298ff7f74f8cc48057ecab20075063a80c2a32f",
"values-night": "d6693cb743ee0ebff12d7ae91e83cabd6bca99c72e151da93fb7b29f9f3748fa"
}
}