Assistant: a bottom sheet over the app, microphone first
CI / check (push) Canceled after 0s

Long-press power opened a full-screen window. The assistant is now a sheet
over the current app (see-through window, own dim): half height, drag the
handle up to full, down / Back / a tap outside to close (settle() decides,
unit-tested). Both ways in -- the voice-interaction session and AssistActivity
-- draw the same AssistSheetFrame + AssistSheetContent, the latter from state
alone for the screenshot tests.

- Microphone first: it opens listening (Settings switch), words shown as they
  come. LLeMbas voice input re-transcribes the recording so far every 1.2 s
  and a pause after speech sends it (RMS level + unchanged words; nothing said
  is discarded, never transcribed); the phone's recogniser gives partials
  itself (PhoneRecognizer: on-device, else another app's -- never the default,
  which is LLeMbas's own while it is the assistant; no Google library).
- Model and connection chip: picture, name, instance, online dot; a tap picks
  another model, kept in Prefs.assistantModel.
- Use screen: the AssistStructure text and/or screenshot, sent only with the
  next question after a tap; quick actions Summarise / Translate / Explain.
- Continue the last assistant chat; follow-ups stay in the same chat until
  New chat. Voice reply through the server's TTS (toggle; Read aloud).
- Open in app continues the same chat. A card waiting for an answer says to
  open it in the app.
- Help line: no wake word for a third-party assistant on stock Android.
- Settings: Voice input (LLeMbas = the instance's speech-to-text via the
  server; Phone = the phone's recogniser) with what each does with the
  recording, and "Start listening when the assistant opens".
- The session makes a fresh controller as it hides, so the next invocation's
  screen lands in the controller that shows it.

Screenshots 18-23 (the sheet over a chat), 08-settings at full length.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Opus 5.5 committed 2026-11-10 08:19:21 +00:00
1 parent 6ae5736ffd
commit 21e5de2d73
24 files changed
+2097 -240

No files matched your search

@@ -8,18 +8,9 @@ import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.imePadding
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.lifecycleScope
import eu.llembas.android.AppLanguage
import eu.llembas.android.auth.Prefs
@@ -28,12 +19,17 @@ import eu.llembas.android.ui.theme.LembasTheme
/**
* The assistant as an activity: what the Quick Settings tile, the "Ask" shortcut and a plain
* `ACTION_ASSIST` open, and where the voice-interaction session hands a question asked over the
* lock screen. Shown over the lock screen, but it asks Android to unlock before it sends
* `ACTION_ASSIST` open, and where the voice-interaction session hands over what needs an
* activity -- a question asked over the lock screen, or the microphone's permission prompt
* ([EXTRA_LISTEN]). The same sheet as the session's, in a see-through window over the app
* underneath. Shown over the lock screen, but it asks Android to unlock before it sends
* anything -- and shows nothing from the account until then.
*/
class AssistActivity : ComponentActivity() {
private lateinit var controller: AssistController
/** Whether the phone is locked: the sheet shows nothing from the account until it is not. */
private val locked = mutableStateOf(false)
private val mic = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) controller.listen()
}
@@ -46,13 +42,16 @@ class AssistActivity : ComponentActivity() {
setShowWhenLocked(true)
controller = AssistController(this, lifecycleScope)
val 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() {
if (waiting.isNotBlank()) controller.ask(waiting)
locked.value = false
if (waiting.isNotBlank()) controller.ask(waiting) else controller.opened(locked = false)
}
override fun onDismissCancelled() = finish()
@@ -62,38 +61,35 @@ class AssistActivity : ComponentActivity() {
)
} else if (waiting.isNotBlank()) {
controller.ask(waiting)
} else if (wantsMic && !controller.micAllowed()) {
mic.launch(Manifest.permission.RECORD_AUDIO)
} else {
controller.opened(locked = false)
}
setContent {
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
LembasTheme(prefs.theme) {
Box(
Modifier
.fillMaxSize()
.background(Color.Black.copy(alpha = 0.4f))
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { finish() }
.imePadding(),
contentAlignment = Alignment.BottomCenter,
) {
Box(Modifier.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}) {
AssistPanel(
controller = controller,
locked = keyguard.isKeyguardLocked,
onUnlockAndAsk = { text ->
keyguard.requestDismissKeyguard(
this@AssistActivity,
object : KeyguardManager.KeyguardDismissCallback() {
override fun onDismissSucceeded() = controller.ask(text)
},
)
AssistPanel(
controller = controller,
locked = locked.value,
onUnlockAndAsk = { text ->
keyguard.requestDismissKeyguard(
this@AssistActivity,
object : KeyguardManager.KeyguardDismissCallback() {
override fun onDismissSucceeded() {
locked.value = false
if (text.isBlank()) controller.opened(locked = false) else controller.ask(text)
}
},
onOpenApp = {
startActivity(controller.appIntent())
finish()
},
onNeedMic = { mic.launch(Manifest.permission.RECORD_AUDIO) },
)
}
}
},
onOpenApp = {
startActivity(controller.appIntent())
finish()
},
onNeedMic = { mic.launch(Manifest.permission.RECORD_AUDIO) },
onDismiss = { finish() },
)
}
}
}
@@ -105,5 +101,8 @@ class AssistActivity : ComponentActivity() {
companion object {
const val EXTRA_QUESTION = "eu.llembas.android.QUESTION"
/** Handed over by the session: ask for the microphone, then listen. */
const val EXTRA_LISTEN = "eu.llembas.android.LISTEN"
}
}
@@ -1,120 +1,385 @@
package eu.llembas.android.assist
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.speech.SpeechRecognizer
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.LiveReply
import eu.llembas.android.api.ModelInfo
import eu.llembas.android.api.Step
import eu.llembas.android.api.StreamClient
import eu.llembas.android.auth.Prefs
import eu.llembas.android.lembas
import eu.llembas.android.push.Notifications
import eu.llembas.android.ui.explain
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import java.io.ByteArrayOutputStream
/** One question asked in the sheet and its answer: written now ([reply]), or read back ([earlier]). */
data class AssistTurn(val question: String, val reply: LiveReply? = null, val earlier: List<Step> = emptyList()) {
val steps: List<Step> get() = reply?.finished?.steps ?: reply?.shown ?: earlier
val writing: Boolean get() = reply != null && reply.finished == null && !reply.closed
}
/** Whether the instance answers: being asked, yes, or no (and why). */
enum class Connection { Checking, Online, Offline }
/** The last chat the assistant made, offered to be continued. */
data class LastAssist(val chatId: String, val title: String, val at: Long)
data class AssistUiState(
val signedIn: Boolean = true,
val instanceName: String = "",
val connection: Connection = Connection.Checking,
val models: List<ModelInfo> = emptyList(),
val modelId: String? = null,
val listening: Boolean = false,
/** The words heard so far, while listening and while the last of them is written down. */
val heard: String = "",
/** How loud the microphone hears it, 0..1. */
val level: Float = 0f,
val busy: Boolean = false,
val asked: String? = null,
val turns: List<AssistTurn> = emptyList(),
val chatId: String? = null,
val reply: LiveReply? = null,
val error: String? = null,
/** Whether the screen goes with the question. Off until the person turns it on, every time. */
val includeScreen: Boolean = false,
val screenAvailable: Boolean = false,
)
val screenText: Boolean = false,
val screenshot: Bitmap? = null,
val last: LastAssist? = null,
/** Whether a spoken question is answered aloud too. */
val voiceReply: Boolean = true,
/** Whether the instance can read aloud (its text-to-speech, for this account). */
val canSpeak: Boolean = false,
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,
) {
val screenAvailable: Boolean get() = screenText || screenshot != null
val modelInfo: ModelInfo? get() = models.firstOrNull { it.id == modelId }
val empty: Boolean get() = turns.isEmpty()
}
/**
* The assistant's one job: take a question -- typed or spoken -- start a chat with it on the
* instance, and stream the answer back into the sheet. Shared by the voice-interaction session
* (power button, assist gesture) and [AssistActivity] (the tile, the shortcut, the lock screen
* path), so both behave the same.
*
* The chat is an ordinary one: it is in the list on the phone and on the web afterwards. The
* Settings switch "assistant chats are temporary" makes them temporary instead.
* What the sheet can do. Every method does nothing by default, so the screenshot tests can draw
* the sheet with no controller behind it.
*/
class AssistController(private val context: Context, private val scope: CoroutineScope) {
interface AssistActions {
fun listen() {}
fun heard() {}
fun type() {}
fun ask(question: String) {}
fun includeScreen(on: Boolean) {}
fun quick(prompt: String) {}
fun continueLast() {}
fun newChat() {}
fun pickModel(id: String) {}
fun voiceReply(on: Boolean) {}
fun readAloud() {}
fun stopReading() {}
}
/**
* The assistant: take a question -- spoken or typed -- start a chat with it on the instance (or
* carry on the one this sheet is in), and stream the answer back into the sheet. Shared by the
* voice-interaction session (power button, assist gesture) and [AssistActivity] (the tile, the
* shortcut, the lock-screen path), so both behave the same.
*
* A chat it makes is an ordinary one: in the list on the phone and on the web afterwards, and
* "Open in app" continues it there. Settings' "assistant chats are temporary" makes them
* temporary instead.
*
* Speech in is Settings › Voice input: the instance's speech-to-text (the words are written down
* a moment behind, from the recording so far, and a pause in speech sends it), or the phone's
* own recogniser (the words as they are said). Speech out is the instance's text-to-speech.
*/
class AssistController(private val context: Context, private val scope: CoroutineScope) : AssistActions {
private val _state = MutableStateFlow(AssistUiState())
val state = _state.asStateFlow()
private val recorder = Recorder(scope)
private val phone = PhoneRecognizer(context)
private val speaker = Speaker(context)
private var following: Job? = null
private var hearing: Job? = null
private var usingPhone = false
private var screenText: String? = null
private var screenshot: Bitmap? = null
private var stt: Boolean? = null
private val ready: Job
init {
scope.launch { _state.update { it.copy(signedIn = context.lembas.instances.current() != null) } }
ready = scope.launch { load() }
scope.launch { speaker.playing.collect { on -> _state.update { it.copy(speaking = on) } } }
}
/** The instance, its models and what it offers this account; the choices kept in Settings. */
private suspend fun load() {
val store = context.lembas.instances
val instance = store.current()
val prefs = store.prefs.first()
_state.update {
it.copy(
signedIn = instance != null,
instanceName = instance?.name?.ifBlank { instance.base }.orEmpty(),
voiceReply = prefs.readAloudSpoken,
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
)
}
val api = instance?.let { store.clientFor(it) } ?: return
try {
val me = api.me()
val models = api.models()
stt = me.services["stt"]
val chosen = prefs.assistantModel.takeIf { id -> models.any { it.id == id } }
?: me.defaultModel?.takeIf { id -> models.any { it.id == id } }
?: models.firstOrNull { it.default }?.id
?: models.firstOrNull()?.id
_state.update {
it.copy(
connection = Connection.Online,
models = models,
modelId = it.modelId ?: chosen,
canSpeak = me.services["tts"] == true,
canListen = me.services["stt"] == true || PhoneRecognizer.available(context),
)
}
} catch (e: Exception) {
_state.update { it.copy(connection = Connection.Offline, error = context.explain(e)) }
}
}
/**
* 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).
*/
fun opened(locked: Boolean) {
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()
}
}
fun micAllowed(): Boolean = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
fun offerScreen(text: String?, image: Bitmap?) {
if (!text.isNullOrBlank()) screenText = text.take(MAX_SCREEN_CHARS)
if (image != null) screenshot = image
_state.update { it.copy(screenAvailable = screenText != null || screenshot != null) }
_state.update { it.copy(screenText = screenText != null, screenshot = image ?: it.screenshot) }
}
fun includeScreen(on: Boolean) = _state.update { it.copy(includeScreen = on) }
override fun includeScreen(on: Boolean) = _state.update { it.copy(includeScreen = on) }
// --- Speech in ---------------------------------------------------------------------------
/** Which recogniser: the one Settings names, else whichever this phone and instance have. */
private suspend fun phoneEngine(): Boolean {
val wanted = context.lembas.instances.prefs.first().voiceInput
val phoneHas = PhoneRecognizer.available(context)
return when {
wanted == Prefs.VOICE_PHONE && phoneHas -> true
stt == false && phoneHas -> true
else -> false
}
}
@android.annotation.SuppressLint("MissingPermission")
fun listen() {
override fun listen() {
if (_state.value.listening || !micAllowed()) return
speaker.stop()
recorder.start()
_state.update { it.copy(listening = true, error = null) }
}
/** Stop listening, write down what was said, and ask it. */
fun heard() {
scope.launch {
val wav = recorder.stop()
_state.update { it.copy(listening = false) }
if (wav.isEmpty()) return@launch
try {
_state.update { it.copy(busy = true) }
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
_state.update { it.copy(busy = false) }
if (text.isNotBlank()) ask(text, spoken = true)
} catch (e: Exception) {
_state.update { it.copy(busy = false, error = context.explain(e)) }
hearing?.cancel()
_state.update { it.copy(listening = true, heard = "", level = 0f, error = null) }
hearing = scope.launch {
usingPhone = phoneEngine()
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)
},
onFail = { code ->
val quiet = code == SpeechRecognizer.ERROR_NO_MATCH || code == SpeechRecognizer.ERROR_SPEECH_TIMEOUT
_state.update {
it.copy(
listening = false,
level = 0f,
error = if (quiet) null else context.getString(R.string.assist_recogniser_failed),
)
}
},
)
} else {
recorder.start()
launch { recorder.level.collect { l -> _state.update { it.copy(level = l) } } }
launch { writeDownAsSaid() }
// Nothing said is nothing sent: a speech-to-text model asked to write down
// silence tends to invent a sentence.
if (untilQuiet()) heard() else type()
}
}
}
fun ask(question: String, spoken: Boolean = false) {
/**
* The instance's speech-to-text takes a whole recording, so words "as they are said" are the
* recording so far, written down again every moment -- one request at a time, only when half
* a second more has been said, and not past the first minute.
*/
private suspend fun writeDownAsSaid() {
val api = context.lembas.instances.client() ?: return
var sent = 0f
while (scope.isActive) {
delay(PARTIAL_EVERY_MS)
val seconds = recorder.seconds
if (seconds - sent < 0.5f || seconds > 60f) continue
sent = seconds
val words = runCatching { api.transcribe(recorder.snapshot()) }.getOrNull()
if (!words.isNullOrBlank() && _state.value.listening) _state.update { it.copy(heard = words) }
}
}
/** Wait for a pause after speech (true) -- or for nothing said at all, which gives up (false). */
private suspend fun untilQuiet(): Boolean {
var spoke = false
var quietFor = 0L
var waited = 0L
// The words written down so far are the second ear, for a quiet microphone: words the
// instance heard mean speech, and the same words for a while mean it ended.
var words = ""
var sameWordsFor = 0L
while (true) {
delay(TICK_MS)
waited += TICK_MS
val level = recorder.level.value
if (level >= SPEAKING) {
spoke = true
quietFor = 0
} else if (level < QUIET) {
quietFor += TICK_MS
}
val heard = _state.value.heard
if (heard.isNotBlank()) spoke = true
if (heard != words) {
words = heard
sameWordsFor = 0
} else if (heard.isNotBlank()) {
sameWordsFor += TICK_MS
}
if (spoke && quietFor >= PAUSE_MS) return true
if (sameWordsFor >= SAME_WORDS_MS) return true
if (!spoke && waited >= NOTHING_SAID_MS) return false
if (waited >= LONGEST_MS) return spoke
}
}
/** Stop listening, write down what was said, and ask it. */
override fun heard() {
if (!_state.value.listening) return
if (usingPhone) {
phone.finish()
return
}
hearing?.cancel()
hearing = null
scope.launch {
val wav = recorder.stop()
_state.update { it.copy(listening = false, level = 0f) }
if (wav.size <= 44 + Recorder.RATE / 2) {
_state.update { it.copy(heard = "") }
return@launch
}
try {
_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)
} catch (e: Exception) {
_state.update { it.copy(busy = false, heard = "", error = context.explain(e)) }
}
}
}
/** Stop listening and keep nothing: the person would rather type. */
override fun type() {
hearing?.cancel()
hearing = null
phone.stop()
scope.launch { recorder.stop() }
_state.update { it.copy(listening = false, heard = "", level = 0f) }
}
// --- Asking ------------------------------------------------------------------------------
override fun ask(question: String) = ask(question, spoken = false)
override fun quick(prompt: String) {
_state.update { it.copy(includeScreen = true) }
ask(prompt, spoken = false)
}
fun ask(question: String, spoken: Boolean) {
if (question.isBlank()) return
if (_state.value.listening) type()
following?.cancel()
following = scope.launch {
_state.update { it.copy(busy = true, asked = question, reply = null, error = null) }
val turn = AssistTurn(question)
_state.update { it.copy(busy = true, turns = it.turns + turn, error = null) }
try {
val api = context.lembas.instances.client() ?: error("Not signed in.")
val prefs = context.lembas.instances.prefs.first()
val withScreen = _state.value.includeScreen
val store = context.lembas.instances
val api = store.client() ?: throw ApiException(401, "Not signed in.")
val prefs = store.prefs.first()
val now = _state.value
val withScreen = now.includeScreen
val attachments = buildList {
if (withScreen) {
screenshot?.let { shot -> add(api.upload("screen.png", "image/png", png(shot)).id) }
}
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
val made = api.createChat(text, attachments, temporary = prefs.assistantTemporary)
_state.update { it.copy(chatId = made.chat.id) }
val reply = made.reply ?: return@launch
var live = LiveReply(reply.id)
StreamClient(api).follow(made.chat.id, reply.id).collect { frame ->
// The screen goes with one question, not every one after it.
_state.update { it.copy(includeScreen = false) }
val chatId = now.chatId
val replyId: String
val inChat: String
if (chatId != null) {
val sent = api.sendMessage(chatId, text, attachments)
inChat = chatId
replyId = sent.reply?.id ?: return@launch
} else {
val made = api.createChat(text, attachments, model = now.modelId, temporary = prefs.assistantTemporary)
inChat = made.chat.id
replyId = made.reply?.id ?: return@launch
_state.update { it.copy(chatId = inChat) }
if (!prefs.assistantTemporary) {
store.savePrefs {
it.copy(lastAssistChat = inChat, lastAssistTitle = question.take(120), lastAssistAt = System.currentTimeMillis())
}
}
}
var live = LiveReply(replyId)
StreamClient(api).follow(inChat, replyId).collect { frame ->
live = live.apply(frame.event, frame.data)
_state.update { it.copy(reply = live, busy = live.finished == null) }
}
val finished = live.finished
if (spoken && prefs.readAloudSpoken && finished != null) {
val words = finished.steps.filter { it.kind == "text" }.joinToString("\n\n") { it.markdown.orEmpty() }
if (words.isNotBlank()) speaker.play(api.speech(plain(words)))
_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()))
} catch (e: Exception) {
_state.update { it.copy(error = context.explain(e)) }
} finally {
@@ -123,6 +388,74 @@ class AssistController(private val context: Context, private val scope: Coroutin
}
}
/** Carry on the last chat the assistant made: its last exchange shown, the next question sent to it. */
override fun continueLast() {
val last = _state.value.last ?: return
scope.launch {
_state.update { it.copy(busy = true, error = null) }
try {
val api = context.lembas.instances.client() ?: return@launch
val detail = api.chat(last.chatId)
val question = detail.messages.lastOrNull { it.isUser }
val answer = detail.messages.lastOrNull { !it.isUser }
val turns = if (question != null) listOf(AssistTurn(question.text.orEmpty(), earlier = answer?.steps.orEmpty())) else emptyList()
_state.update { it.copy(chatId = last.chatId, turns = turns, modelId = detail.chat.model.ifBlank { null } ?: it.modelId, last = null) }
} catch (e: Exception) {
// A chat deleted since is simply not offered again.
if (e is ApiException && e.status == 404) {
context.lembas.instances.savePrefs { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) }
_state.update { it.copy(last = null) }
} else {
_state.update { it.copy(error = context.explain(e)) }
}
} finally {
_state.update { it.copy(busy = false) }
}
}
}
override fun newChat() {
following?.cancel()
speaker.stop()
_state.update { it.copy(chatId = null, turns = emptyList(), error = null, busy = false) }
}
/** The model: for the chat this sheet is in, changed at once; for a new one, kept for next time. */
override fun pickModel(id: String) {
_state.update { it.copy(modelId = id) }
scope.launch {
context.lembas.instances.savePrefs { it.copy(assistantModel = id) }
val chat = _state.value.chatId ?: return@launch
runCatching { context.lembas.instances.client()?.updateChat(chat, JsonObject(mapOf("model" to JsonPrimitive(id)))) }
.onFailure { e -> _state.update { it.copy(error = context.explain(e)) } }
}
}
// --- Speech out --------------------------------------------------------------------------
override fun voiceReply(on: Boolean) {
if (!on) speaker.stop()
_state.update { it.copy(voiceReply = on) }
scope.launch { context.lembas.instances.savePrefs { it.copy(readAloudSpoken = on) } }
}
override fun readAloud() {
val steps = _state.value.turns.lastOrNull()?.steps ?: return
scope.launch { speak(spokenWords(steps)) }
}
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))
} catch (e: Exception) {
_state.update { it.copy(error = context.explain(e)) }
}
}
/** Carry on in the app, at this chat. The caller starts it: a session and an activity
* start activities differently. */
fun appIntent(): Intent = Intent(context, MainActivity::class.java)
@@ -131,7 +464,9 @@ class AssistController(private val context: Context, private val scope: Coroutin
fun close() {
following?.cancel()
hearing?.cancel()
speaker.stop()
phone.stop()
scope.launch { recorder.stop() }
}
@@ -145,6 +480,21 @@ class AssistController(private val context: Context, private val scope: Coroutin
companion object {
const val MAX_SCREEN_CHARS = 8_000
// Listening, for the instance's speech-to-text (the phone's recogniser finds the end of
// speech itself). Levels are the RMS of 16-bit samples, 0..1: a room is under 0.01,
// a voice near the phone 0.02 and up. Not tuned on many phones: the stop button always works.
private const val TICK_MS = 100L
private const val SPEAKING = 0.02f
private const val QUIET = 0.01f
private const val PAUSE_MS = 1_800L
private const val SAME_WORDS_MS = 4_500L
private const val NOTHING_SAID_MS = 8_000L
private const val LONGEST_MS = 120_000L
private const val PARTIAL_EVERY_MS = 1_200L
/** A reply's words, for a voice: its text steps, without the markup. */
fun spokenWords(steps: List<Step>): String = plain(steps.filter { it.kind == "text" }.joinToString("\n\n") { it.markdown.orEmpty() })
/** Markdown as something a voice can read: no fences, marks or link targets. */
fun plain(markdown: String): String = markdown
.replace(Regex("```[\\s\\S]*?```"), " ")
@@ -1,120 +1,40 @@
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
package eu.llembas.android.assist
import android.Manifest
import android.content.pm.PackageManager
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import eu.llembas.android.R
import eu.llembas.android.ui.chat.Steps
/**
* The assistant's sheet: a question box, the microphone, "Include screen", and the answer as it
* is written. Nothing from the account -- no chat list, no history -- is on it, which is what
* lets it open over the lock screen (sending from there asks to unlock first: [locked]).
* The assistant's sheet with its [controller] behind it: [AssistSheetFrame] over the current app,
* [AssistSheetContent] in it. The session and [AssistActivity] differ only in what the four
* callbacks do: over the lock screen nothing is sent before Android unlocks ([onUnlockAndAsk]);
* the microphone's permission prompt needs an activity ([onNeedMic]).
*/
@Composable
fun AssistPanel(controller: AssistController, locked: Boolean, onUnlockAndAsk: (String) -> Unit, onOpenApp: () -> Unit, onNeedMic: () -> Unit) {
fun AssistPanel(
controller: AssistController,
locked: Boolean,
onUnlockAndAsk: (String) -> Unit,
onOpenApp: () -> Unit,
onNeedMic: () -> Unit,
onDismiss: () -> Unit,
) {
val state by controller.state.collectAsState()
val context = LocalContext.current
var text by remember { mutableStateOf("") }
val focus = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { focus.requestFocus() } }
Surface(
shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp),
tonalElevation = 3.dp,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(16.dp).navigationBarsPadding(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
if (!state.signedIn) {
Text(stringResource(R.string.assist_signed_out))
TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_open_app)) }
return@Column
}
state.asked?.let { Text(it, style = MaterialTheme.typography.titleSmall) }
if (state.busy) LinearProgressIndicator(Modifier.fillMaxWidth())
state.reply?.let { reply ->
Column(Modifier.heightIn(max = 420.dp).verticalScroll(rememberScrollState())) {
Steps(reply.finished?.steps ?: reply.shown)
AssistSheetFrame(onDismiss = onDismiss) { handle, _ ->
AssistSheetContent(
state = state,
actions = controller,
locked = locked,
handle = handle,
onOpenApp = onOpenApp,
onSend = { text -> if (locked) onUnlockAndAsk(text) else controller.ask(text) },
onMic = {
when {
locked -> onUnlockAndAsk("")
controller.micAllowed() -> controller.listen()
else -> onNeedMic()
}
}
state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
if (state.screenAvailable && !locked) {
FilterChip(
selected = state.includeScreen,
onClick = { controller.includeScreen(!state.includeScreen) },
label = { Text(stringResource(R.string.assist_include_screen)) },
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
TextField(
value = text,
onValueChange = { text = it },
placeholder = { Text(stringResource(if (state.listening) R.string.listening else R.string.assist_hint)) },
modifier = Modifier.weight(1f).focusRequester(focus),
)
IconButton(onClick = {
when {
locked -> onUnlockAndAsk(text)
state.listening -> controller.heard()
ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) ==
PackageManager.PERMISSION_GRANTED -> controller.listen()
else -> onNeedMic()
}
}) {
Icon(if (state.listening) Icons.Filled.Stop else Icons.Filled.Mic, contentDescription = stringResource(R.string.dictate))
}
IconButton(enabled = text.isNotBlank() && !state.busy, onClick = {
if (locked) onUnlockAndAsk(text) else controller.ask(text)
text = ""
}) {
Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
}
}
if (state.chatId != null) {
TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_open_in_app)) }
}
}
},
)
}
}
@@ -5,13 +5,17 @@ import android.app.assist.AssistStructure
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.service.voice.VoiceInteractionService
import android.service.voice.VoiceInteractionSession
import android.service.voice.VoiceInteractionSessionService
import android.view.View
import android.view.WindowManager
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.core.view.WindowCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
@@ -55,6 +59,7 @@ class LembasAssistSession(context: Context) :
private val saved = SavedStateRegistryController.create(this)
private var scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private var controller = AssistController(context, scope)
private val current = mutableStateOf(controller)
override val lifecycle: Lifecycle get() = registry
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
@@ -63,6 +68,15 @@ class LembasAssistSession(context: Context) :
super.onCreate()
saved.performRestore(null)
registry.currentState = Lifecycle.State.CREATED
// A see-through window over the whole screen: the sheet draws its own dim and sits at
// the bottom, the app underneath stays in sight, and the sheet moves with the keyboard.
window.window?.let { w ->
w.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
w.setDimAmount(0f)
WindowCompat.setDecorFitsSystemWindows(w, false)
@Suppress("DEPRECATION")
w.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
}
}
override fun onCreateContentView(): View {
@@ -74,15 +88,18 @@ class LembasAssistSession(context: Context) :
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnDetachedFromWindow)
setContent {
LembasTheme(theme) {
// The controller is made again for each showing: read it from state, so the
// sheet follows the new one.
AssistPanel(
controller = controller,
controller = current.value,
locked = locked(),
onUnlockAndAsk = { text -> handOff(text) },
onOpenApp = {
startAssistantActivity(controller.appIntent())
startAssistantActivity(current.value.appIntent())
hide()
},
onNeedMic = { handOff("") },
onNeedMic = { handOff("", listen = true) },
onDismiss = { hide() },
)
}
}
@@ -91,16 +108,22 @@ class LembasAssistSession(context: Context) :
override fun onShow(args: Bundle?, showFlags: Int) {
super.onShow(args, showFlags)
if (!scope.isActiveScope()) {
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
controller = AssistController(context, scope)
}
registry.currentState = Lifecycle.State.RESUMED
controller.opened(locked())
}
/**
* Each showing starts fresh -- a new question, the screen not included, listening first --
* so a new controller is made as this one hides: ready for the screen the next invocation
* hands over, which may come before or after its `onShow`.
*/
override fun onHide() {
super.onHide()
controller.close()
scope.cancel()
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
controller = AssistController(context, scope)
current.value = controller
registry.currentState = Lifecycle.State.CREATED
}
@@ -121,7 +144,7 @@ class LembasAssistSession(context: Context) :
controller.offerScreen(text, null)
}
/** And a picture of it, if allowed ("Use screenshot"). Sent only when "Include screen" is on. */
/** And a picture of it, if allowed ("Use screenshot"). Sent only when "Use screen" is on. */
override fun onHandleScreenshot(screenshot: Bitmap?) {
super.onHandleScreenshot(screenshot)
controller.offerScreen(null, screenshot)
@@ -140,14 +163,13 @@ class LembasAssistSession(context: Context) :
* which asks Android to unlock first and only then sends it. The microphone's permission
* prompt needs an activity too.
*/
private fun handOff(text: String) {
private fun handOff(text: String, listen: Boolean = false) {
startAssistantActivity(
Intent(context, AssistActivity::class.java)
.putExtra(AssistActivity.EXTRA_QUESTION, text)
.putExtra(AssistActivity.EXTRA_LISTEN, listen)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
hide()
}
private fun CoroutineScope.isActiveScope(): Boolean = coroutineContext[kotlinx.coroutines.Job]?.isActive == true
}
@@ -0,0 +1,564 @@
package eu.llembas.android.assist
import android.text.format.DateUtils
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material.icons.automirrored.filled.Send
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.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.ScreenshotMonitor
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material.icons.filled.Summarize
import androidx.compose.material.icons.filled.Translate
import androidx.compose.material3.AssistChip
import androidx.compose.material3.AssistChipDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
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.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.llembas.android.R
import eu.llembas.android.ui.ModelAvatar
import eu.llembas.android.ui.chat.Steps
import eu.llembas.android.ui.theme.LocalPalette
import kotlinx.coroutines.launch
/** Where a let-go drag leaves the sheet. */
enum class SheetStop { Half, Full, Gone }
/**
* Where the sheet goes when a drag of its handle ends at [height] px moving at [velocity] px/s
* (positive is down), between [half] and [full]: a fling decides by its direction, a slow
* release by the nearest stop -- and below most of the half, it goes.
*/
fun settle(height: Float, half: Float, full: Float, velocity: Float): SheetStop = when {
velocity > FLING -> if (height < half + 1f) SheetStop.Gone else SheetStop.Half
velocity < -FLING -> SheetStop.Full
height < half * 0.6f -> SheetStop.Gone
height > (half + full) / 2f -> SheetStop.Full
else -> SheetStop.Half
}
private const val FLING = 1_200f
/**
* The assistant's window: the app it opened over stays in sight under a dim, and the sheet rises
* from the bottom to about half the height. Its handle drags it to the full height or down and
* away; a tap on the dim, or Back, closes it too. With the keyboard up, the sheet's stops are
* measured above the keyboard.
*/
@Composable
fun AssistSheetFrame(onDismiss: () -> Unit, content: @Composable ColumnScope.(handle: Modifier, expanded: Boolean) -> Unit) {
val palette = LocalPalette.current
val inspection = LocalInspectionMode.current
val scope = rememberCoroutineScope()
val top = WindowInsets.statusBars.asPaddingValues().calculateTopPadding()
Box(
Modifier
.fillMaxSize()
.background(Color.Black.copy(alpha = 0.32f))
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onDismiss)
.imePadding(),
) {
BoxWithConstraints(Modifier.fillMaxSize()) {
val density = LocalDensity.current
val full = with(density) { (maxHeight - top - 8.dp).toPx() }.coerceAtLeast(0f)
val half = (full * 0.56f).coerceAtLeast(minOf(full, with(density) { 360.dp.toPx() }))
var expanded by remember { mutableStateOf(false) }
val target = if (expanded) full else half
val height = remember { Animatable(if (inspection) target else 0f) }
LaunchedEffect(target) { height.animateTo(target) }
val drag = rememberDraggableState { delta -> scope.launch { height.snapTo((height.value - delta).coerceIn(0f, full)) } }
val handle = Modifier.draggable(
drag,
Orientation.Vertical,
onDragStopped = { velocity ->
when (settle(height.value, half, full, velocity)) {
SheetStop.Gone -> {
height.animateTo(0f)
onDismiss()
}
SheetStop.Full -> {
expanded = true
height.animateTo(full)
}
SheetStop.Half -> {
expanded = false
height.animateTo(half)
}
}
},
)
Surface(
color = palette.surface,
contentColor = palette.ink,
shape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp),
tonalElevation = 2.dp,
shadowElevation = 8.dp,
modifier = Modifier
.align(Alignment.BottomCenter)
.fillMaxWidth()
.height(with(density) { height.value.toDp() })
// Taps inside the sheet are the sheet's, not the dim's.
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {},
) {
Column(Modifier.fillMaxSize().navigationBarsPadding()) { content(handle, expanded) }
}
}
}
}
/**
* The sheet's contents, from [state] alone (what the screenshot tests draw):
*
* - **the top**: the drag handle, the model and connection chip (the model's picture, its name,
* the instance and whether it answers; a tap picks another model), voice reply on or off, and
* Open in app, which carries on this same chat in the app;
* - **the middle**: before anything is asked, the last assistant chat to continue, the quick
* actions (the screen's, when the system handed one over), and how to open the assistant --
* and that there is no wake word; then the questions and answers, the answers as they are
* written;
* - **the foot**: Use screen, then the microphone first -- while listening, the words as they are
* heard and how loud -- or the words typed, and Send.
*
* Nothing from the account is on it while the phone is [locked]: no model list, no last chat.
*/
@Composable
fun ColumnScope.AssistSheetContent(
state: AssistUiState,
actions: AssistActions,
locked: Boolean,
handle: Modifier = Modifier,
onOpenApp: () -> Unit = {},
onSend: (String) -> Unit = actions::ask,
onMic: () -> Unit = actions::listen,
) {
val palette = LocalPalette.current
var text by remember { mutableStateOf("") }
val scroll = rememberScrollState()
val growth = state.turns.lastOrNull()?.steps?.sumOf { (it.markdown?.length ?: 0) + (it.text?.length ?: 0) } ?: 0
LaunchedEffect(state.turns.size, growth) { if (state.turns.isNotEmpty()) scroll.animateScrollTo(scroll.maxValue) }
// The top: the handle and the bar. Both drag the sheet.
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)))
}
Row(Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) {
val showChip = state.signedIn && !locked
Box(Modifier.weight(1f)) {
if (showChip) {
ModelChip(state, actions)
} else {
Text(stringResource(R.string.app_name), style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(8.dp))
}
}
if (state.canSpeak && !locked) {
IconButton(onClick = { actions.voiceReply(!state.voiceReply) }) {
Icon(
if (state.voiceReply) Icons.AutoMirrored.Filled.VolumeUp else Icons.AutoMirrored.Filled.VolumeOff,
contentDescription = stringResource(if (state.voiceReply) R.string.assist_voice_reply_on else R.string.assist_voice_reply_off),
tint = if (state.voiceReply) palette.accent else palette.inkMuted,
)
}
}
if (state.signedIn) {
IconButton(onClick = onOpenApp) {
Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = stringResource(R.string.assist_open_in_app), tint = palette.inkMuted)
}
}
}
if (state.busy) {
LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(2.dp))
} else {
Spacer(Modifier.height(2.dp))
}
}
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)
Spacer(Modifier.height(8.dp))
TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_open_app)) }
}
return
}
// The middle.
Column(
Modifier.weight(1f).fillMaxWidth().verticalScroll(scroll).padding(horizontal = 16.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
if (state.empty) {
Starting(state, actions, locked)
} else {
state.turns.forEachIndexed { i, turn ->
Turn(turn, last = i == state.turns.lastIndex, state, actions, onOpenApp)
}
}
state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
}
// The foot.
Column(Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, top = 4.dp, bottom = 12.dp)) {
if (state.screenAvailable && !locked) ScreenToggle(state, actions)
if (state.listening) {
Listening(state, onDone = actions::heard, onType = actions::type)
} else {
val focus = remember { FocusRequester() }
Row(verticalAlignment = Alignment.CenterVertically) {
TextField(
value = text,
onValueChange = { text = it },
placeholder = { Text(stringResource(if (state.busy && state.heard.isNotBlank()) R.string.assist_writing_down else R.string.assist_hint)) },
shape = RoundedCornerShape(24.dp),
colors = TextFieldDefaults.colors(
focusedContainerColor = palette.surfaceRaised,
unfocusedContainerColor = palette.surfaceRaised,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
),
maxLines = 4,
modifier = Modifier.weight(1f).heightIn(min = 52.dp).focusRequester(focus),
)
Spacer(Modifier.width(8.dp))
// One slot of fixed size: the microphone, or Send once there are words.
Box(Modifier.size(52.dp), contentAlignment = Alignment.Center) {
if (text.isBlank()) {
if (state.canListen) {
Surface(
onClick = onMic,
shape = CircleShape,
color = palette.accent,
contentColor = palette.accentInk,
modifier = Modifier.size(52.dp),
) {
Box(contentAlignment = Alignment.Center) { Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.dictate)) }
}
}
} else {
Surface(
onClick = {
onSend(text)
text = ""
},
enabled = !state.busy || locked,
shape = CircleShape,
color = palette.accent,
contentColor = palette.accentInk,
modifier = Modifier.size(52.dp),
) {
Box(contentAlignment = Alignment.Center) {
Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
}
}
}
}
}
if (state.heard.isNotBlank()) {
Text(state.heard, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, modifier = Modifier.padding(start = 16.dp, top = 6.dp))
}
}
}
}
/** The model and the connection: its picture, its name, the instance and a dot that says whether it answers. */
@Composable
private fun ModelChip(state: AssistUiState, actions: AssistActions) {
val palette = LocalPalette.current
var open by remember { mutableStateOf(false) }
val dot = when (state.connection) {
Connection.Online -> palette.success
Connection.Offline -> palette.danger
Connection.Checking -> palette.inkFaint
}
val where = when (state.connection) {
Connection.Online -> state.instanceName
Connection.Offline -> stringResource(R.string.assist_offline, state.instanceName)
Connection.Checking -> stringResource(R.string.assist_connecting)
}
Box {
Surface(
onClick = { if (state.models.isNotEmpty()) open = true },
shape = RoundedCornerShape(24.dp),
color = palette.surfaceRaised,
border = BorderStroke(1.dp, palette.border),
modifier = Modifier.widthIn(max = 320.dp).heightIn(min = 48.dp),
) {
Row(Modifier.padding(start = 6.dp, end = 4.dp, top = 6.dp, bottom = 6.dp), verticalAlignment = Alignment.CenterVertically) {
Box {
ModelAvatar(state.modelInfo, state.modelId ?: "?", size = 32.dp)
// The connection's dot, ringed in the chip's colour so it reads over any picture.
val ring = Modifier.align(Alignment.BottomEnd).size(10.dp).clip(CircleShape).background(palette.surfaceRaised)
Box(ring.padding(2.dp).clip(CircleShape).background(dot))
}
Spacer(Modifier.width(10.dp))
Column(Modifier.weight(1f, fill = false)) {
Text(
state.modelInfo?.name?.ifBlank { null } ?: state.modelId ?: stringResource(R.string.assist_no_model),
style = MaterialTheme.typography.titleSmall,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(where, style = MaterialTheme.typography.labelSmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
Icon(Icons.Filled.ArrowDropDown, contentDescription = null, tint = palette.inkMuted)
}
}
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
state.models.forEach { model ->
DropdownMenuItem(
leadingIcon = { ModelAvatar(model, model.id, size = 24.dp) },
text = { Text(model.name.ifBlank { model.id }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
trailingIcon = if (model.id == state.modelId) {
{ Box(Modifier.size(8.dp).clip(CircleShape).background(palette.accent)) }
} else {
null
},
onClick = {
open = false
actions.pickModel(model.id)
},
)
}
}
}
}
/** Before anything is asked: the last chat to continue, the quick actions, and how to open this. */
@Composable
private fun Starting(state: AssistUiState, actions: AssistActions, locked: Boolean) {
val palette = LocalPalette.current
if (!locked) {
state.last?.let { last ->
Surface(
onClick = actions::continueLast,
shape = RoundedCornerShape(20.dp),
color = palette.surfaceRaised,
border = BorderStroke(1.dp, palette.border),
modifier = Modifier.fillMaxWidth(),
) {
Row(Modifier.padding(horizontal = 16.dp, vertical = 12.dp).heightIn(min = 40.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Filled.History, contentDescription = null, tint = palette.accent)
Spacer(Modifier.width(16.dp))
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.assist_continue), style = MaterialTheme.typography.titleSmall)
Text(
listOf(last.title, if (last.at > 0) DateUtils.getRelativeTimeSpanString(last.at).toString() else "")
.filter { it.isNotBlank() }.joinToString(" · "),
style = MaterialTheme.typography.bodyMedium,
color = palette.inkMuted,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
}
if (state.screenAvailable && !locked) {
val summarise = stringResource(R.string.assist_quick_summarise_prompt)
val translate = stringResource(R.string.assist_quick_translate_prompt)
val explain = stringResource(R.string.assist_quick_explain_prompt)
Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
QuickAction(Icons.Filled.Summarize, stringResource(R.string.assist_quick_summarise)) { actions.quick(summarise) }
QuickAction(Icons.Filled.Translate, stringResource(R.string.assist_quick_translate)) { actions.quick(translate) }
QuickAction(Icons.Filled.Lightbulb, stringResource(R.string.assist_quick_explain)) { actions.quick(explain) }
}
}
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)
}
}
@Composable
private fun QuickAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, onClick: () -> Unit) {
val palette = LocalPalette.current
AssistChip(
onClick = onClick,
label = { Text(label) },
leadingIcon = { Icon(icon, contentDescription = null, modifier = Modifier.size(18.dp)) },
colors = AssistChipDefaults.assistChipColors(containerColor = palette.surfaceRaised, leadingIconContentColor = palette.accent),
border = BorderStroke(1.dp, palette.border),
modifier = Modifier.heightIn(min = 40.dp),
)
}
/** One question, as a bubble on the right, and its answer at full width -- as in the app's chats. */
@Composable
private fun Turn(turn: AssistTurn, last: Boolean, state: AssistUiState, actions: AssistActions, onOpenApp: () -> Unit) {
val palette = LocalPalette.current
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) {
Surface(color = palette.bubbleUser, contentColor = palette.ink, shape = RoundedCornerShape(20.dp), modifier = Modifier.widthIn(max = 300.dp)) {
Text(turn.question, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
}
}
if (turn.steps.isNotEmpty()) Steps(turn.steps)
val reply = turn.reply
when {
reply != null && reply.cards.isNotEmpty() -> TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_answer_in_app)) }
turn.writing && reply?.status?.isNotBlank() == true -> Text(reply.status, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
last && !turn.writing && turn.steps.isNotEmpty() -> Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (state.canSpeak) {
if (state.speaking) {
AssistChip(onClick = actions::stopReading, label = { Text(stringResource(R.string.assist_stop_reading)) }, leadingIcon = {
Icon(Icons.Filled.Stop, contentDescription = null, modifier = Modifier.size(18.dp))
})
} else {
AssistChip(onClick = actions::readAloud, label = { Text(stringResource(R.string.assist_read_aloud)) }, leadingIcon = {
Icon(Icons.AutoMirrored.Filled.VolumeUp, contentDescription = null, modifier = Modifier.size(18.dp))
})
}
}
AssistChip(onClick = actions::newChat, label = { Text(stringResource(R.string.new_chat)) }, leadingIcon = {
Icon(Icons.Filled.EditNote, contentDescription = null, modifier = Modifier.size(18.dp))
})
}
}
}
}
/** 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) {
val palette = LocalPalette.current
Row(Modifier.fillMaxWidth().padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
FilterChip(
selected = state.includeScreen,
onClick = { actions.includeScreen(!state.includeScreen) },
label = { Text(stringResource(R.string.assist_use_screen)) },
leadingIcon = { Icon(Icons.Filled.ScreenshotMonitor, contentDescription = null, modifier = Modifier.size(18.dp)) },
colors = FilterChipDefaults.filterChipColors(selectedContainerColor = palette.accentSoft, selectedLeadingIconColor = palette.accent),
modifier = Modifier.heightIn(min = 40.dp),
)
if (state.includeScreen) {
Spacer(Modifier.width(10.dp))
state.screenshot?.let { shot ->
Image(
shot.asImageBitmap(),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.size(width = 24.dp, height = 40.dp).clip(RoundedCornerShape(4.dp)).background(palette.bgSunken),
)
Spacer(Modifier.width(8.dp))
}
Text(
stringResource(
when {
state.screenText && state.screenshot != null -> R.string.assist_screen_both
state.screenText -> R.string.assist_screen_text
else -> R.string.assist_screen_shot
},
),
style = MaterialTheme.typography.bodySmall,
color = palette.inkMuted,
modifier = Modifier.weight(1f),
)
}
}
}
/**
* Listening: the microphone, grown by how loud it hears you (a tap sends what was said), the
* words so far, and the keyboard to type instead. The row's parts keep their sizes; the words
* give.
*/
@Composable
private fun Listening(state: AssistUiState, onDone: () -> Unit, onType: () -> Unit) {
val palette = LocalPalette.current
Row(Modifier.fillMaxWidth().heightIn(min = 72.dp), verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.size(64.dp), contentAlignment = Alignment.Center) {
Box(Modifier.size(64.dp).scale(0.8f + 0.2f * (state.level * 3f).coerceAtMost(1f)).clip(CircleShape).background(palette.accentSoft))
Surface(onClick = onDone, shape = CircleShape, color = palette.accent, contentColor = palette.accentInk, modifier = Modifier.size(52.dp)) {
Box(contentAlignment = Alignment.Center) { Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.assist_send_now)) }
}
}
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.listening), style = MaterialTheme.typography.labelLarge, color = palette.accent)
Text(
state.heard.ifBlank { stringResource(R.string.assist_say_it) },
style = MaterialTheme.typography.bodyLarge,
color = if (state.heard.isBlank()) palette.inkFaint else palette.ink,
maxLines = 4,
overflow = TextOverflow.Ellipsis,
)
}
IconButton(onClick = onType) { Icon(Icons.Filled.Keyboard, contentDescription = stringResource(R.string.assist_type), tint = palette.inkMuted) }
}
}
@@ -1,16 +1,27 @@
package eu.llembas.android.assist
import android.Manifest
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaPlayer
import android.media.MediaRecorder
import android.os.Build
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognitionService
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import androidx.annotation.RequiresPermission
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -31,9 +42,19 @@ class Recorder(private val scope: CoroutineScope) {
private var record: AudioRecord? = null
private var job: Job? = null
private val pcm = ByteArrayOutputStream()
private val _level = MutableStateFlow(0f)
/** How loud the last moment was, 0..1 (RMS of the samples): the sheet's meter and its ear for silence. */
val level: StateFlow<Float> = _level.asStateFlow()
val recording: Boolean get() = record != null
/** What has been said so far, as a WAV file, without stopping: for words shown as they come. */
fun snapshot(): ByteArray = pcm.toByteArray().let { if (it.isEmpty()) it else wav(it) }
/** How many seconds have been recorded. */
val seconds: Float get() = pcm.size() / (RATE * 2f)
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
fun start() {
if (record != null) return
@@ -54,6 +75,7 @@ class Recorder(private val scope: CoroutineScope) {
val read = audio.read(buffer, 0, buffer.size)
if (read > 0) {
pcm.write(buffer, 0, read)
_level.value = rms(buffer, read)
} else if (read < 0) {
break
}
@@ -71,6 +93,7 @@ class Recorder(private val scope: CoroutineScope) {
job?.cancel()
job?.join()
audio.release()
_level.value = 0f
val body = pcm.toByteArray()
pcm.reset()
return if (body.isEmpty()) body else wav(body)
@@ -80,6 +103,18 @@ class Recorder(private val scope: CoroutineScope) {
const val RATE = 16_000
private const val MAX_BYTES = RATE * 2 * 120 // two minutes
/** The loudness of [length] bytes of 16-bit little-endian samples, 0..1. */
fun rms(buffer: ByteArray, length: Int): Float {
val samples = length / 2
if (samples == 0) return 0f
var sum = 0.0
for (i in 0 until samples) {
val sample = ((buffer[i * 2 + 1].toInt() shl 8) or (buffer[i * 2].toInt() and 0xFF)).toShort() / 32768.0
sum += sample * sample
}
return kotlin.math.sqrt(sum / samples).toFloat().coerceIn(0f, 1f)
}
fun wav(pcm: ByteArray): ByteArray {
val header = ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
put("RIFF".toByteArray())
@@ -101,9 +136,11 @@ class Recorder(private val scope: CoroutineScope) {
}
}
/** Speech out: the instance's text-to-speech, played once. */
/** Speech out: the instance's text-to-speech, played once. [playing] is true while it speaks. */
class Speaker(private val context: Context) {
private var player: MediaPlayer? = null
private val _playing = MutableStateFlow(false)
val playing: StateFlow<Boolean> = _playing.asStateFlow()
suspend fun play(mp3: ByteArray) {
stop()
@@ -120,10 +157,12 @@ class Speaker(private val context: Context) {
it.release()
file.delete()
player = null
_playing.value = false
}
prepare()
start()
}
_playing.value = true
}
fun stop() {
@@ -132,5 +171,109 @@ class Speaker(private val context: Context) {
release()
}
player = null
_playing.value = false
}
}
/**
* 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.
*
* While LLeMbas is the digital assistant the *system's* default recogniser is LLeMbas's own
* ([LembasRecognitionService]), so this never asks for the default: it takes the on-device
* recogniser (Android 12+), else another installed app's. No Google library is linked; a
* phone without any recogniser simply has none to offer ([available]).
*/
class PhoneRecognizer(private val context: Context) {
private var recognizer: SpeechRecognizer? = null
fun start(onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit) {
stop()
startWith(onDevice(context), onPartial, onLevel, onResult, onFail)
}
// `onFail`, not `onError`: inside the listener below that name is the listener's own method.
private fun startWith(onDevice: Boolean, onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit) {
val other = component(context)
val made = when {
onDevice && Build.VERSION.SDK_INT >= 31 -> SpeechRecognizer.createOnDeviceSpeechRecognizer(context)
other != null -> SpeechRecognizer.createSpeechRecognizer(context, other)
else -> return onFail(SpeechRecognizer.ERROR_CLIENT)
}
recognizer = made
made.setRecognitionListener(
object : RecognitionListener {
override fun onReadyForSpeech(params: Bundle?) {}
override fun onBeginningOfSpeech() {}
// About -2 dB in silence to 10 dB speaking: the meter's 0..1.
override fun onRmsChanged(rmsdB: Float) = onLevel(((rmsdB + 2f) / 12f).coerceIn(0f, 1f))
override fun onBufferReceived(buffer: ByteArray?) {}
override fun onEndOfSpeech() = onLevel(0f)
override fun onError(error: Int) {
// The on-device recogniser lacks this language: another app's may have it.
if (onDevice && other != null && (error == LANGUAGE_NOT_SUPPORTED || error == LANGUAGE_UNAVAILABLE)) {
stop()
startWith(false, onPartial, onLevel, onResult, onFail)
return
}
stop()
onFail(error)
}
override fun onResults(results: Bundle?) {
val text = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull().orEmpty()
stop()
onResult(text)
}
override fun onPartialResults(partialResults: Bundle?) {
partialResults?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()
?.takeIf { it.isNotBlank() }?.let(onPartial)
}
override fun onEvent(eventType: Int, params: Bundle?) {}
},
)
made.startListening(
Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.packageName),
)
}
/** Stop listening now; what was heard comes to `onResult`. */
fun finish() {
recognizer?.stopListening()
}
fun stop() {
recognizer?.runCatching {
cancel()
destroy()
}
recognizer = null
}
companion object {
// SpeechRecognizer.ERROR_LANGUAGE_NOT_SUPPORTED and ERROR_LANGUAGE_UNAVAILABLE (API 31).
private const val LANGUAGE_NOT_SUPPORTED = 12
private const val LANGUAGE_UNAVAILABLE = 13
private fun onDevice(context: Context): Boolean = Build.VERSION.SDK_INT >= 31 && SpeechRecognizer.isOnDeviceRecognitionAvailable(context)
/** Another app's recogniser -- never LLeMbas's own, which would send it back to the instance. */
fun component(context: Context): ComponentName? = context.packageManager
.queryIntentServices(Intent(RecognitionService.SERVICE_INTERFACE), 0)
.map { ComponentName(it.serviceInfo.packageName, it.serviceInfo.name) }
.firstOrNull { it.packageName != context.packageName }
/** Whether this phone has a recogniser of its own to offer. */
fun available(context: Context): Boolean = onDevice(context) || component(context) != null
}
}
@@ -70,6 +70,11 @@ private val PREFS = stringPreferencesKey("prefs")
* What the person chose in Settings, for this phone. [language]: "" the account's language (the
* default), "system" the phone's, or a language's code -- see [eu.llembas.android.AppLanguage].
* [accountLanguage] is the account's language as the instance in use last said it.
*
* The assistant's: [voiceInput] `lembas` (the instance's speech-to-text) or `phone` (the phone's
* recogniser); [assistantListens] whether it opens listening; [assistantModel] the model it
* starts chats on ("" the account's default); and the last chat it made, which its sheet
* offers to continue ([lastAssistChat], its first question, when).
*/
@Serializable
data class Prefs(
@@ -78,7 +83,18 @@ data class Prefs(
val readAloudSpoken: Boolean = true,
val language: String = "",
val accountLanguage: String = "",
)
val voiceInput: String = VOICE_LEMBAS,
val assistantListens: Boolean = true,
val assistantModel: String = "",
val lastAssistChat: String = "",
val lastAssistTitle: String = "",
val lastAssistAt: Long = 0,
) {
companion object {
const val VOICE_LEMBAS = "lembas"
const val VOICE_PHONE = "phone"
}
}
class InstanceStore(private val context: Context) {
private val listSerializer = ListSerializer(Instance.serializer())
@@ -27,10 +27,13 @@ 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.CheckCircle
import androidx.compose.material.icons.filled.Dns
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Mic
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.SystemUpdate
import androidx.compose.material.icons.filled.Timer
@@ -68,6 +71,7 @@ import androidx.compose.ui.unit.dp
import eu.llembas.android.AppLanguage
import eu.llembas.android.BuildConfig
import eu.llembas.android.R
import eu.llembas.android.assist.PhoneRecognizer
import eu.llembas.android.auth.Instance
import eu.llembas.android.auth.Prefs
import eu.llembas.android.lembas
@@ -87,6 +91,8 @@ interface SettingsActions {
fun notificationSettings() {}
fun assistantSettings() {}
fun assistantTemporary(on: Boolean) {}
fun voiceInput(value: String) {}
fun assistantListens(on: Boolean) {}
fun readAloud(on: Boolean) {}
fun checkUpdate() {}
}
@@ -101,6 +107,8 @@ data class SettingsState(
val updateNote: String? = null,
val version: String = "",
val selfUpdate: Boolean = false,
/** Whether the phone has a speech recogniser of its own (Settings › Voice input › Phone). */
val phoneRecognizer: Boolean = false,
)
@Composable
@@ -161,6 +169,14 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
scope.launch { store.savePrefs { it.copy(assistantTemporary = on) } }
}
override fun voiceInput(value: String) {
scope.launch { store.savePrefs { it.copy(voiceInput = value) } }
}
override fun assistantListens(on: Boolean) {
scope.launch { store.savePrefs { it.copy(assistantListens = on) } }
}
override fun readAloud(on: Boolean) {
scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } }
}
@@ -180,6 +196,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
updateNote = updateNote,
version = BuildConfig.VERSION_NAME,
selfUpdate = BuildConfig.SELF_UPDATE,
phoneRecognizer = remember { PhoneRecognizer.available(context) },
),
actions,
onBack,
@@ -325,6 +342,13 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
trailing = { Switch(checked = state.prefs.assistantTemporary, onCheckedChange = actions::assistantTemporary) },
)
Rule()
SettingRow(
Icons.Filled.Mic,
stringResource(R.string.assistant_listens),
onClick = { actions.assistantListens(!state.prefs.assistantListens) },
trailing = { Switch(checked = state.prefs.assistantListens, onCheckedChange = actions::assistantListens) },
)
Rule()
SettingRow(
Icons.Filled.RecordVoiceOver,
stringResource(R.string.assistant_read_aloud),
@@ -333,7 +357,43 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
)
}
Text(
stringResource(R.string.assistant_samsung),
stringResource(R.string.assistant_samsung) + "\n\n" + stringResource(R.string.assist_no_wake_word),
style = MaterialTheme.typography.bodySmall,
color = palette.inkFaint,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
}
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.
Group(stringResource(R.string.voice_input)) {
SettingRow(
Icons.Filled.Dns,
stringResource(R.string.voice_input_lembas),
subtitle = stringResource(R.string.voice_input_lembas_line),
onClick = { actions.voiceInput(Prefs.VOICE_LEMBAS) },
trailing = {
RadioButton(selected = state.prefs.voiceInput != Prefs.VOICE_PHONE, onClick = { actions.voiceInput(Prefs.VOICE_LEMBAS) })
},
)
Rule()
SettingRow(
Icons.Filled.PhoneAndroid,
stringResource(R.string.voice_input_phone),
subtitle = stringResource(if (state.phoneRecognizer) R.string.voice_input_phone_line else R.string.voice_input_phone_none),
enabled = state.phoneRecognizer,
onClick = { actions.voiceInput(Prefs.VOICE_PHONE) },
trailing = {
RadioButton(
selected = state.prefs.voiceInput == Prefs.VOICE_PHONE,
enabled = state.phoneRecognizer,
onClick = { actions.voiceInput(Prefs.VOICE_PHONE) },
)
},
)
}
Text(
stringResource(R.string.voice_input_hint),
style = MaterialTheme.typography.bodySmall,
color = palette.inkFaint,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),