Assistant entry points: share sheet (new or last chat), widget, shortcuts, headset button
CI / check (push) Canceled after 0s
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>
This commit is contained in:
38 files changed
+964
-135
No files matched your search
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
@@ -17,6 +18,33 @@ import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
|
||||
/** 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
|
||||
* `ACTION_ASSIST` open, and where the voice-interaction session hands over what needs an
|
||||
@@ -27,6 +55,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 +70,9 @@ 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)
|
||||
}
|
||||
take(intent)
|
||||
setContent {
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
LembasTheme(prefs.theme) {
|
||||
@@ -94,6 +101,50 @@ 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() {
|
||||
controller.close()
|
||||
super.onDestroy()
|
||||
@@ -104,5 +155,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)
|
||||
}
|
||||
}
|
||||
@@ -168,14 +168,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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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) }
|
||||
|
||||
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.
|
||||
val last = state.last
|
||||
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,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()
|
||||
}
|
||||
Reference in new issue
Block a user