Andee lives on your phone or Mac and uses any app like you do—no integrations, no root, any model; memory and passwords never leave your device | Andee 住进你的手机或 Mac,像你一样操作任何 App——无需集成、无需 Root、支持任意模型,记忆和密码绝不离开设备。
feat(input): send photos from the typing field, with or without words
booboosui2459afa1e24f
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 8646572..a9ed564 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -181,17 +181,30 @@because on this ROM an overlay window cannot raise the softkeyboard — measured; see ui/TextInputActivity. Translucent so theapp behind stays visible: this adds a field, it does not take the- screen. -->+ screen. Not noHistory: that finishes it the moment the camera or+ the photo picker opens, and their result would have nowhere to+ land. onStop does the same job and knows when not to. --><activityandroid:name=".ui.TextInputActivity"android:theme="@android:style/Theme.Translucent.NoTitleBar"android:excludeFromRecents="true"- android:noHistory="true"android:launchMode="singleTop"android:windowSoftInputMode="adjustResize"android:exported="false"android:configChanges="orientation|screenSize|keyboardHidden" />+ <!-- Where the system camera writes a photo taken from the typing+ field. Cache only; the file is deleted once it is encoded. -->+ <provider+ android:name="androidx.core.content.FileProvider"+ android:authorities="${applicationId}.files"+ android:exported="false"+ android:grantUriPermissions="true">+ <meta-data+ android:name="android.support.FILE_PROVIDER_PATHS"+ android:resource="@xml/file_paths" />+ </provider>+</application></manifest>diff --git a/app/src/main/java/net/kuafuai/andee/ScreenBodyService.kt b/app/src/main/java/net/kuafuai/andee/ScreenBodyService.ktindex 567bb83..bab10b6 100644--- a/app/src/main/java/net/kuafuai/andee/ScreenBodyService.kt+++ b/app/src/main/java/net/kuafuai/andee/ScreenBodyService.kt@@ -308,7 +308,10 @@ class ScreenBodyService : AccessibilityService() {// The field the user types into. A window of its own, and an Activity// rather than an overlay — an overlay window cannot raise the soft// keyboard on this ROM. See ui/TextInputActivity.- net.kuafuai.andee.ui.TextInputActivity.onSubmit = { submitUserTurn(it, "typed") }+ net.kuafuai.andee.ui.TextInputActivity.onSubmit = { text, images -> submitUserTurn(text, "typed", images) }+ // The camera and the photo picker are other apps' windows, and the card+ // is an overlay that sorts above them — so it steps aside while they are up.+ net.kuafuai.andee.ui.TextInputActivity.onAway = { window.setAway(it) }// Fires on every way out of the field; see [typingFinished].net.kuafuai.andee.ui.TextInputActivity.onClosed = { typingFinished() }// And this is how the card knows where to stop: the field's own top@@ -703,10 +706,10 @@ class ScreenBodyService : AccessibilityService() {** [how] is only for the log line.*/- private fun submitUserTurn(text: String, how: String) {+ private fun submitUserTurn(text: String, how: String, images: List<String> = emptyList()) {val said = text.trim()- if (said.isEmpty()) return- android.util.Log.i("Body", "$how: $said")+ if (said.isEmpty() && images.isEmpty()) return+ android.util.Log.i("Body", "$how: $said" + if (images.isEmpty()) "" else " (+${images.size} images)")// Hand the keyboard back before the turn exists: the brain may call// `type_text` inside it, and it can only do that on ADBKeyboard.closeTyping()@@ -717,18 +720,23 @@ class ScreenBodyService : AccessibilityService() {val editing = pendingArtifactpendingArtifact = nullval forBrain = editing?.let { artifactEditQuery(it, said) } ?: said+ val row = if (editing != null) AppLocale.str(this, R.string.artifacts_edit_said, editing.text, said) else saidnet.kuafuai.andee.ui.ChatHistory.addUser(- if (editing != null) AppLocale.str(this, R.string.artifacts_edit_said, editing.text, said) else said,+ if (images.isEmpty()) row+ else "${AppLocale.str(this, R.string.input_photos_row, images.size)} $row".trim(),)+ // The hub gets the count, not the pixels: an event is fire-and-forget,+ // and megabytes of base64 on it would be dropped along with the text.val payload = org.json.JSONObject().put("text", forBrain).put("ts", System.currentTimeMillis())+ if (images.isNotEmpty()) payload.put("images", images.size)hubClient?.sendEvent("asr.final", payload)wsServer?.broadcastEvent("asr.final", payload)// Same turn, different brain. The local one takes the text directly —// there is no socket in between, and no event kind it would have to be// taught (see the meeting callback).- localBrain?.submit(forBrain)+ localBrain?.submit(forBrain, images)// Task start, and deliberately at the request rather than at the// reply: from here the device is being worked on, whether that reaches// us as a tool call or as thirty seconds of thinking. Nobody listening@@ -792,6 +800,7 @@ class ScreenBodyService : AccessibilityService() {*/private fun typingFinished() {window.setTypingTop(0)+ window.setAway(false)if (typingFromFullscreen && !window.isCompact()) dispatcher.expand()typingFromFullscreen = false}diff --git a/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.kt b/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.ktindex cbd7f91..09cf7c7 100644--- a/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.kt+++ b/app/src/main/java/net/kuafuai/andee/brain/LocalBrain.kt@@ -206,9 +206,17 @@ class LocalBrain(/** Image messages currently in [history], oldest first. See [trimImages]. */private val imageMessages = mutableListOf<JSONObject>()- fun submit(userText: String) {+ /**+ * Photo messages the *user* attached, oldest first. Kept apart from+ * [imageMessages] so a task's screenshots cannot evict the very photo the+ * task is about; see [attachUserPhotos].+ */+ private val photoMessages = mutableListOf<JSONObject>()++ /** [images] are base64 JPEGs; with any of them, [userText] may be empty. */+ fun submit(userText: String, images: List<String> = emptyList()) {val text = userText.trim()- if (text.isEmpty()) return+ if (text.isEmpty() && images.isEmpty()) returnif (cfg.apiKey.isEmpty()) {// Said out loud rather than logged: from the ball's point of view a// missing key is indistinguishable from a brain that never answers.@@ -220,7 +228,7 @@ class LocalBrain(// must not look like the user spoke, or it would keep pushing its own// trigger out.net.kuafuai.andee.config.Notebook.touchActivity(appContext)- launch(text, TurnKind.USER)+ launch(text, TurnKind.USER, images)}/**@@ -300,14 +308,14 @@ class LocalBrain(* it, draining queued wakes, harvesting, telling the service the turn is* over — is here once, so no entry point can forget a step.*/- private fun launch(text: String, kind: TurnKind) {+ private fun launch(text: String, kind: TurnKind, images: List<String> = emptyList()) {val gen = generation.incrementAndGet()loop.execute {busy.set(true)currentKind = kindturnTokens = 0try {- runTurn(text, gen, kind)+ runTurn(text, gen, kind, images)} catch (t: Throwable) {if (gen == generation.get()) {Log.e(TAG, "turn $gen ($kind) failed", t)@@ -399,7 +407,7 @@ class LocalBrain(// the loop// ------------------------------------------------------------------- private fun runTurn(userText: String, gen: Int, kind: TurnKind) {+ private fun runTurn(userText: String, gen: Int, kind: TurnKind, images: List<String> = emptyList()) {val internal = kind.silentval harvest = kind == TurnKind.HARVESTif (history.isEmpty()) {@@ -433,6 +441,14 @@ class LocalBrain(// Empty notebook, empty string, zero cost: the feature only starts// paying for itself once there is something to remember.val index = net.kuafuai.andee.config.Notebook.indexForPrompt(appContext)+ // Photos with no words: there is no sentence of the user's to take+ // the language from, so the bracketed fallback comes back for it.+ val wordless = userText.isEmpty()+ val said = if (wordless) {+ "(the user sent ${images.size} photo(s) with no words — they are attached right below; answer what they most likely want)"+ } else {+ userText+ }JSONObject().put("role", "user").put(@@ -455,7 +471,7 @@ class LocalBrain(// is the answer and absent when there is a better one, and// the model is never asked to arbitrate between two."content",- "[now ${stamp()}${if (kind == TurnKind.USER) "" else " · ui-language ${uiLangTag()}"}] $userText" ++ "[now ${stamp()}${if (kind == TurnKind.USER && !wordless) "" else " · ui-language ${uiLangTag()}"}] $said" +if (index.isEmpty()) {""} else {@@ -464,6 +480,8 @@ class LocalBrain()}+ if (!internal && images.isNotEmpty()) attachUserPhotos(images)+val tools = LlmClient.toolSpecs(ToolSchemas.all(), registry.tools())var lastSignature = ""var repeats = 0@@ -708,6 +726,32 @@ class LocalBrain(trimImages()}+ /**+ * The user's own photos, as a vision message right behind their words.+ *+ * Behind rather than inside: the words stay a plain-string `user` message,+ * which is what [isBoundary] cuts at, and this one is then dropped together+ * with them by [trimHistory]. Only the newest batch survives — a photo the+ * user sent ten minutes ago is not worth re-uploading on every request.+ */+ private fun attachUserPhotos(images: List<String>) {+ val content = JSONArray()+ // "这是什么" next to a photo is exactly the trigger `camera_turn`'s+ // description names, so say outright that the seeing is already done.+ content.put(+ LlmClient.textBlock(+ "The ${images.size} photo(s) the user attached to the message above. " ++ "You can already see them here — \"这个 / this\" means these photos. " ++ "Do NOT open the camera or take a screenshot to look at them.",+ ),+ )+ for (b64 in images) content.put(LlmClient.imageBlock(b64, "image/jpeg"))+ val msg = JSONObject().put("role", "user").put("content", content)+ history += msg+ photoMessages += msg+ while (photoMessages.size > MAX_PHOTO_MESSAGES) history.remove(photoMessages.removeAt(0))+ }+/*** Keep only the newest [MAX_IMAGE_MESSAGES] image messages, dropping the* older ones from the history entirely.@@ -791,6 +835,7 @@ class LocalBrain(private fun drop(index: Int) {val gone = history.removeAt(index)imageMessages.remove(gone)+ photoMessages.remove(gone)}// ------------------------------------------------------------------@@ -900,6 +945,7 @@ class LocalBrain(// longer exist, or [trimImages] would later try to remove an object// twice and drop a live message with it.imageMessages.retainAll { msg -> history.any { it === msg } }+ photoMessages.retainAll { msg -> history.any { it === msg } }lastHarvestAtSize = history.sizeLog.i(TAG,@@ -1040,6 +1086,7 @@ class LocalBrain(private const val MAX_IMAGE_MESSAGES = 2private const val MAX_IMAGES_PER_STEP = 2+ private const val MAX_PHOTO_MESSAGES = 1private const val MAX_TOOL_CHARS = 24_000/**diff --git a/app/src/main/java/net/kuafuai/andee/net/ToolSchemas.kt b/app/src/main/java/net/kuafuai/andee/net/ToolSchemas.ktindex 0905031..79a291d 100644--- a/app/src/main/java/net/kuafuai/andee/net/ToolSchemas.kt+++ b/app/src/main/java/net/kuafuai/andee/net/ToolSchemas.kt@@ -733,6 +733,9 @@ object ToolSchemas {as a screenshot). The session STAYS OPEN between calls.WHEN TO USE — you decide the cadence, fit it to the ask:+ - NOT when the user's message came with attached photos: then+ "这是什么/看看这个" is about those photos, which you can already+ see. Answer from them; never open the camera for them.- "这是什么/看看这个" → look once, answer. If the frame is blurry orthe target isn't in view, TELL the user to aim ("对准一点") andlook again.diff --git a/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt b/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.ktindex 6a9c84c..1b27429 100644--- a/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt+++ b/app/src/main/java/net/kuafuai/andee/ui/FloatingWindowUi.kt@@ -213,6 +213,9 @@ class FloatingWindowUi(private var captureHidden = falseprivate var compact = false+ /** The typing field has sent the user to a camera or a photo picker. See [setAway]. */+ private var away = false+/** The typing field's top edge, in screen px. 0 = no field is up. */private var typingTop = 0@@ -879,6 +882,22 @@ class FloatingWindowUi(}}+ /**+ * Vanish while the typing field has the user in another app's camera or+ * photo picker. The card still holds its typing height, which puts it over+ * the top of that app, and overlays sort above activities; it is already+ * untouchable while a field is up, so alpha 0 is all that is missing.+ * Separate from [captureHidden] so a screenshot finishing mid-pick cannot+ * bring the card back over the picker.+ */+ fun setAway(away: Boolean) {+ ui.post {+ if (this.away == away) return@post+ this.away = away+ applyWindow()+ }+ }+/*** Fold to the corner ball so the user sees — and can touch — the real app* underneath. The card covers the whole screen and is not meaningfully@@ -1748,7 +1767,7 @@ class FloatingWindowUi(private fun applyWindow() {val v = root ?: returnval p = params ?: return- p.alpha = if (captureHidden) 0f else 1f+ p.alpha = if (captureHidden || away) 0f else 1f// FLAG_LAYOUT_IN_SCREEN is what makes the unfolded card actually// fullscreen. Without it the window's frame is the *content* area —// the display minus the status and navigation bars — so a MATCH_PARENT@@ -1783,7 +1802,7 @@ class FloatingWindowUi(// full screen of pixels nobody can see. Turning it off here is also what// makes the card look the same on a device where cross-window blur is// unavailable, which is most of them.- val wantFrost = !compact && !captureHidden && !backdropUp()+ val wantFrost = !compact && !captureHidden && !away && !backdropUp()frosted = Glass.frost(context, wm, p, want = wantFrost)paintCard()// The card now runs under the status bar ([FLAG_LAYOUT_IN_SCREEN]), sodiff --git a/app/src/main/java/net/kuafuai/andee/ui/TextInputActivity.kt b/app/src/main/java/net/kuafuai/andee/ui/TextInputActivity.ktindex 38915b8..1597a44 100644--- a/app/src/main/java/net/kuafuai/andee/ui/TextInputActivity.kt+++ b/app/src/main/java/net/kuafuai/andee/ui/TextInputActivity.kt@@ -1,12 +1,23 @@package net.kuafuai.andee.ui+import android.Manifestimport android.app.Activityimport android.content.Contextimport android.content.Intent+import android.content.pm.PackageManager+import android.graphics.Bitmapimport android.graphics.Color+import android.graphics.ImageDecoderimport android.graphics.drawable.ColorDrawable+import android.graphics.drawable.GradientDrawable+import android.media.ThumbnailUtils+import android.net.Uri+import android.os.Buildimport android.os.Bundle+import android.provider.MediaStoreimport android.text.InputType+import android.util.Base64+import android.util.Logimport android.view.Gravityimport android.view.Viewimport android.view.WindowManager@@ -14,15 +25,21 @@ import android.view.inputmethod.EditorInfoimport android.view.inputmethod.InputMethodManagerimport android.widget.EditTextimport android.widget.FrameLayout+import android.widget.HorizontalScrollViewimport android.widget.ImageViewimport android.widget.LinearLayoutimport android.widget.TextView+import androidx.core.content.FileProviderimport androidx.core.view.ViewCompatimport androidx.core.view.WindowCompatimport androidx.core.view.WindowInsetsCompatimport net.kuafuai.andee.Rimport net.kuafuai.andee.i18n.AppLocale+import java.io.ByteArrayOutputStream+import java.io.Fileimport java.lang.ref.WeakReference+import java.util.concurrent.Executors+import kotlin.math.roundToInt/*** The field a person types into — an **Activity**, not an overlay window.@@ -84,6 +101,32 @@ class TextInputActivity : Activity() {/** Pending "the keyboard is really gone, close up" check. See [scheduleCloseWhenGone]. */private var closeWhenGone: Runnable? = null+ /** A photo ready to go: what the brain gets, and what the strip shows. */+ private class Photo(val jpegBase64: String, val thumb: Bitmap)++ private val photos = mutableListOf<Photo>()+ private lateinit var strip: LinearLayout+ private lateinit var thumbs: LinearLayout+ private lateinit var thumbScroll: HorizontalScrollView++ /** Whether the card should follow the strip's top edge right now. */+ private var trackTop = false++ /**+ * The user is in the camera, the photo picker or the permission dialog.+ * While it is set, the keyboard going away and this activity stopping are+ * both expected, and neither may close the field.+ */+ private var picking = false++ /** Where the system camera was told to write. */+ private var shotFile: File? = null++ /** Images still being decoded; [send] waits for them rather than dropping them. */+ private var decoding = 0+ private var sendWhenDecoded = false+ private val worker = Executors.newSingleThreadExecutor()+override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)lctx = AppLocale.wrap(this)@@ -120,6 +163,25 @@ class TextInputActivity : Activity() {val row = LinearLayout(this).apply {orientation = LinearLayout.HORIZONTALgravity = Gravity.CENTER_VERTICAL+ }+ row.addView(iconButton(R.drawable.ic_camera, lctx.getString(R.string.input_take_photo)) { takePhoto() })+ row.addView(iconButton(R.drawable.ic_image, lctx.getString(R.string.input_pick_photos)) { pickPhotos() })+ row.addView(field, LinearLayout.LayoutParams(0, WRAP, 1f))+ row.addView(glyph(lctx.getString(R.string.input_send), Glass.ACCENT) { send() })+ row.addView(glyph("✕", Glass.LABEL) { finish() })++ thumbs = LinearLayout(this).apply {+ orientation = LinearLayout.HORIZONTAL+ setPadding(dp(4), dp(4), dp(4), dp(8))+ }+ thumbScroll = HorizontalScrollView(this).apply {+ isHorizontalScrollBarEnabled = false+ visibility = View.GONE+ addView(thumbs)+ }++ strip = LinearLayout(this).apply {+ orientation = LinearLayout.VERTICAL// The *card* fill, not `Glass.panel`.//// `Glass` is a two-layer stack: an almost-opaque black base, then@@ -139,10 +201,9 @@ class TextInputActivity : Activity() {// at. A dark bar over the bottom edge is the honest answer.background = Glass.card(this@TextInputActivity, dp(20), frosted = false)setPadding(dp(8), dp(8), dp(8), dp(8))+ addView(thumbScroll, LinearLayout.LayoutParams(MATCH_PARENT, WRAP))+ addView(row, LinearLayout.LayoutParams(MATCH_PARENT, WRAP))}- row.addView(field, LinearLayout.LayoutParams(0, WRAP, 1f))- row.addView(glyph(lctx.getString(R.string.input_send), Glass.ACCENT) { send() })- row.addView(glyph("✕", Glass.LABEL) { finish() })// The strip sits on **the card's own backdrop**, not on the user's app.//@@ -174,7 +235,7 @@ class TextInputActivity : Activity() {orientation = LinearLayout.VERTICALgravity = Gravity.BOTTOMsetPadding(dp(12), dp(4), dp(12), dp(12))- addView(row, LinearLayout.LayoutParams(MATCH_PARENT, WRAP))+ addView(strip, LinearLayout.LayoutParams(MATCH_PARENT, WRAP))}val root = FrameLayout(this).apply {setBackgroundColor(Color.parseColor(Glass.CARD_SOLID))@@ -207,7 +268,12 @@ class TextInputActivity : Activity() {if (ime > 0) {imeShown = truecancelCloseWhenGone()- } else if (imeShown) {+ } else if (picking) {+ // Off in the camera or the picker; the keyboard left with us+ // and comes back in onResume. Leave the card's height alone.+ trackTop = false+ return@setOnApplyWindowInsetsListener insets+ } else if (imeShown && photos.isEmpty()) {// The keyboard is on its way out, and so is this field:收起键盘// means the user is done typing, and a strip left behind on an// otherwise empty screen is a thing to dismiss twice.@@ -217,6 +283,11 @@ class TextInputActivity : Activity() {// of the screen, the card would grow to meet it, and the whole// thing would close a moment later — three moves for one// gesture. Left alone, the card simply grows back once.+ //+ // Not with photos on the strip, though: those took a trip to+ // another app to collect, and losing them to a dropped keyboard+ // is worse than a strip that waits at the bottom for 发送.+ trackTop = falsescheduleCloseWhenGone()return@setOnApplyWindowInsetsListener insets}@@ -225,14 +296,14 @@ class TextInputActivity : Activity() {// position until this pass has laid it out — and sent again on every// inset change, which is what keeps the two in step as the keyboard// slides up and as 搜狗's toolbar row comes and goes.- root.post {- if (isFinishing) return@post- val at = IntArray(2)- row.getLocationOnScreen(at)- onTop?.invoke(at[1])- }+ trackTop = true+ root.post { reportTop() }insets}+ // The strip also grows by itself, when the first photo arrives.+ strip.addOnLayoutChangeListener { _, _, top, _, _, _, oldTop, _, _ ->+ if (top != oldTop && trackTop) reportTop()+ }window.decorView.hideFromAccessibility()OwnCard.shown()live = WeakReference(this)@@ -259,8 +330,16 @@ class TextInputActivity : Activity() {super.onPause()}+ /** What `noHistory` used to do, minus the trips this field sends the user on. */+ override fun onStop() {+ super.onStop()+ if (!picking && !isFinishing) finish()+ }+override fun onDestroy() {cancelCloseWhenGone()+ worker.shutdownNow()+ shotFile?.delete()if (live?.get() === this) live = nullresumed = falseOwnCard.hidden()@@ -275,21 +354,214 @@ class TextInputActivity : Activity() {}/**- * Hand the text to the service and get out of the way.+ * Hand the text and the photos to the service and get out of the way.*+ * Photos alone are a complete message — "what is this", without the words.* Clears the field before handing it over, so a send that turns out to be a* no-op (nothing listening) is visible as an empty box rather than as text* that silently went nowhere.*/private fun send() {+ if (decoding > 0) {+ sendWhenDecoded = true+ return+ }val text = field.text?.toString()?.trim().orEmpty()- if (text.isEmpty()) return+ if (text.isEmpty() && photos.isEmpty()) return+ val images = photos.map { it.jpegBase64 }field.setText("")sent = true- onSubmit?.invoke(text)+ onSubmit?.invoke(text, images)finish()}+ private fun takePhoto() {+ if (photos.size + decoding >= MAX_PHOTOS) return+ if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {+ goAway()+ requestPermissions(arrayOf(Manifest.permission.CAMERA), REQ_CAMERA_PERMISSION)+ return+ }+ val dir = File(cacheDir, "shots").apply { mkdirs() }+ val file = File(dir, "shot-${System.currentTimeMillis()}.jpg")+ val uri = FileProvider.getUriForFile(this, "$packageName.files", file)+ val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)+ .putExtra(MediaStore.EXTRA_OUTPUT, uri)+ .addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)+ goAway()+ if (runCatching { startActivityForResult(intent, REQ_CAMERA) }.isFailure) {+ Log.w(TAG, "no camera app to take a photo with")+ comeBack()+ return+ }+ shotFile = file+ }++ /**+ * The system photo picker where there is one (no storage permission, and+ * it is the picker people already know); `GET_CONTENT` below API 33.+ */+ private fun pickPhotos() {+ val room = MAX_PHOTOS - photos.size - decoding+ if (room <= 0) return+ val intent = if (Build.VERSION.SDK_INT >= 33) {+ Intent(MediaStore.ACTION_PICK_IMAGES).apply {+ // The picker rejects a limit of 1; leaving it out means "one".+ if (room > 1) putExtra(MediaStore.EXTRA_PICK_IMAGES_MAX, room)+ }+ } else {+ Intent(Intent.ACTION_GET_CONTENT)+ .setType("image/*")+ .addCategory(Intent.CATEGORY_OPENABLE)+ .putExtra(Intent.EXTRA_ALLOW_MULTIPLE, room > 1)+ }+ goAway()+ if (runCatching { startActivityForResult(intent, REQ_PICK) }.isFailure) {+ Log.w(TAG, "no photo picker")+ comeBack()+ }+ }++ private fun goAway() {+ picking = true+ cancelCloseWhenGone()+ onAway?.invoke(true)+ }++ private fun comeBack() {+ picking = false+ onAway?.invoke(false)+ }++ override fun onRequestPermissionsResult(code: Int, permissions: Array<out String>, results: IntArray) {+ super.onRequestPermissionsResult(code, permissions, results)+ if (code != REQ_CAMERA_PERMISSION) return+ comeBack()+ if (results.firstOrNull() == PackageManager.PERMISSION_GRANTED) takePhoto()+ }++ @Deprecated("Activity has no other way to get a result without androidx.activity")+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {+ super.onActivityResult(requestCode, resultCode, data)+ comeBack()+ when (requestCode) {+ REQ_CAMERA -> {+ val file = shotFile+ shotFile = null+ if (file == null) return+ if (resultCode == RESULT_OK && file.length() > 0) {+ load(Uri.fromFile(file), file)+ } else {+ file.delete()+ }+ }+ REQ_PICK -> {+ if (resultCode != RESULT_OK || data == null) return+ val uris = mutableListOf<Uri>()+ data.clipData?.let { clip ->+ for (i in 0 until clip.itemCount) clip.getItemAt(i).uri?.let { uris += it }+ }+ if (uris.isEmpty()) data.data?.let { uris += it }+ uris.take(MAX_PHOTOS - photos.size - decoding).forEach { load(it, null) }+ }+ }+ }++ /**+ * Decode off the main thread, at screenshot size: 1280 on the long side+ * is what the brain already reads every screen at, and a 12-megapixel+ * original would be a few megabytes of base64 for no more understanding.+ * `ImageDecoder` applies the EXIF rotation, so a portrait photo arrives+ * upright.+ */+ private fun load(uri: Uri, deleteAfter: File?) {+ decoding+++ val thumbPx = dp(THUMB_DP)+ worker.execute {+ val result = runCatching {+ val bmp = ImageDecoder.decodeBitmap(ImageDecoder.createSource(contentResolver, uri)) { d, info, _ ->+ d.allocator = ImageDecoder.ALLOCATOR_SOFTWARE+ val w = info.size.width+ val h = info.size.height+ val long = maxOf(w, h)+ if (long > PHOTO_LONG_SIDE) {+ val s = PHOTO_LONG_SIDE.toFloat() / long+ d.setTargetSize((w * s).roundToInt().coerceAtLeast(1), (h * s).roundToInt().coerceAtLeast(1))+ }+ }+ val out = ByteArrayOutputStream()+ bmp.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, out)+ val thumb = ThumbnailUtils.extractThumbnail(bmp, thumbPx, thumbPx)+ if (thumb !== bmp) bmp.recycle()+ Photo(Base64.encodeToString(out.toByteArray(), Base64.NO_WRAP), thumb)+ }+ deleteAfter?.delete()+ runOnUiThread {+ decoding--+ result.onSuccess { addPhoto(it) }+ .onFailure { Log.w(TAG, "could not read $uri: ${it.message}") }+ if (decoding == 0 && sendWhenDecoded) {+ sendWhenDecoded = false+ send()+ }+ }+ }+ }++ private fun addPhoto(p: Photo) {+ if (isFinishing || photos.size >= MAX_PHOTOS) return+ photos += p+ val size = dp(THUMB_DP)+ val cell = FrameLayout(this)+ val image = ImageView(this).apply {+ setImageBitmap(p.thumb)+ scaleType = ImageView.ScaleType.CENTER_CROP+ background = GradientDrawable().apply { cornerRadius = dp(10).toFloat() }+ clipToOutline = true+ }+ cell.addView(image, FrameLayout.LayoutParams(size, size))+ val remove = TextView(this).apply {+ text = "✕"+ textSize = 11f+ setTextColor(Color.WHITE)+ gravity = Gravity.CENTER+ background = GradientDrawable().apply {+ shape = GradientDrawable.OVAL+ setColor(Color.parseColor("#CC000000"))+ }+ setOnClickListener {+ photos.remove(p)+ thumbs.removeView(cell)+ syncPhotos()+ }+ }+ cell.addView(+ remove,+ FrameLayout.LayoutParams(dp(22), dp(22), Gravity.TOP or Gravity.END).apply {+ topMargin = dp(3)+ marginEnd = dp(3)+ },+ )+ thumbs.addView(+ cell,+ LinearLayout.LayoutParams(size, size).apply { marginEnd = dp(8) },+ )+ syncPhotos()+ thumbScroll.post { thumbScroll.fullScroll(View.FOCUS_RIGHT) }+ }++ private fun syncPhotos() {+ thumbScroll.visibility = if (photos.isEmpty()) View.GONE else View.VISIBLE+ field.hint = lctx.getString(if (photos.isEmpty()) R.string.input_hint else R.string.input_hint_photos)+ }++ private fun reportTop() {+ if (isFinishing) return+ val at = IntArray(2)+ strip.getLocationOnScreen(at)+ onTop?.invoke(at[1])+ }+/*** Close up once the keyboard is really gone, rather than on the first frame* it reports 0.@@ -305,7 +577,7 @@ class TextInputActivity : Activity() {* cancels it.*/private fun scheduleCloseWhenGone() {- if (closeWhenGone != null || isFinishing) return+ if (closeWhenGone != null || isFinishing || picking) returnval r = Runnable {closeWhenGone = nullif (!isFinishing) finish()@@ -341,10 +613,31 @@ class TextInputActivity : Activity() {setOnClickListener { onClick() }}+ private fun iconButton(icon: Int, label: String, onClick: () -> Unit): ImageView =+ ImageView(this).apply {+ setImageResource(icon)+ setColorFilter(Color.parseColor(Glass.LABEL))+ contentDescription = label+ setPadding(dp(8), dp(10), dp(8), dp(10))+ isClickable = true+ isFocusable = true+ Glass.pressable(this)+ setOnClickListener { onClick() }+ layoutParams = LinearLayout.LayoutParams(dp(40), dp(44))+ }+private fun dp(v: Int): Int = (v * resources.displayMetrics.density).toInt()companion object {+ private const val TAG = "Body"private const val IME_RETRY_MS = 250L+ private const val MAX_PHOTOS = 6+ private const val PHOTO_LONG_SIDE = 1280+ private const val JPEG_QUALITY = 85+ private const val THUMB_DP = 64+ private const val REQ_CAMERA = 1+ private const val REQ_PICK = 2+ private const val REQ_CAMERA_PERMISSION = 3/*** How long the keyboard has to stay gone before the field follows it.@@ -355,9 +648,17 @@ class TextInputActivity : Activity() {private const val WRAP = LinearLayout.LayoutParams.WRAP_CONTENTprivate const val MATCH_PARENT = LinearLayout.LayoutParams.MATCH_PARENT- /** Set once by the service, like [ChatHistory.init]. */+ /** Set once by the service, like [ChatHistory.init]. Text may be empty when photos are not. */+ @Volatile+ var onSubmit: ((String, List<String>) -> Unit)? = null++ /**+ * The field is sending the user to the camera / photo picker (true) or+ * has them back (false). The card above has to vanish meanwhile: it is+ * an overlay and would sit over the top of whatever app opens.+ */@Volatile- var onSubmit: ((String) -> Unit)? = null+ var onAway: ((Boolean) -> Unit)? = null/*** Fires from [onDestroy] — the field is gone, whatever took it away.diff --git a/app/src/main/res/drawable/ic_camera.xml b/app/src/main/res/drawable/ic_camera.xmlnew file mode 100644index 0000000..62cf87d--- /dev/null+++ b/app/src/main/res/drawable/ic_camera.xml@@ -0,0 +1,12 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M12,15.2a3.2,3.2 0,1 0,0 -6.4a3.2,3.2 0,1 0,0 6.4z"/>+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M9,2L7.17,4H4c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V6c0,-1.1 -0.9,-2 -2,-2h-3.17L15,2H9zM12,17c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5z"/>+</vector>diff --git a/app/src/main/res/drawable/ic_image.xml b/app/src/main/res/drawable/ic_image.xmlnew file mode 100644index 0000000..c490417--- /dev/null+++ b/app/src/main/res/drawable/ic_image.xml@@ -0,0 +1,9 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M21,19V5c0,-1.1 -0.9,-2 -2,-2H5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2zM8.5,13.5l2.5,3.01L14.5,12l4.5,6H5l3.5,-4.5z"/>+</vector>diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xmlindex 9499d72..993478e 100644--- a/app/src/main/res/values-en/strings.xml+++ b/app/src/main/res/values-en/strings.xml@@ -251,6 +251,10 @@<string name="bubble_tap_to_talk">Tap to talk</string><string name="input_hint">Type to talk to it…</string><string name="input_send">Send</string>+ <string name="input_hint_photos">Send as is, or add a few words…</string>+ <string name="input_take_photo">Take photo</string>+ <string name="input_pick_photos">Choose images</string>+ <string name="input_photos_row">[%1$d image(s)]</string><string name="cam_close">✕ Done</string><!-- ScreenBodyService.kt — display-only; see the comment on the Chinese side. -->diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 8c289cf..8db47ba 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -228,6 +228,10 @@<string name="bubble_tap_to_talk">点击说话</string><string name="input_hint">打字跟它说…</string><string name="input_send">发送</string>+ <string name="input_hint_photos">可以直接发送,或者补一句…</string>+ <string name="input_take_photo">拍照</string>+ <string name="input_pick_photos">选图片</string>+ <string name="input_photos_row">[%1$d 张图片]</string><string name="cam_close">✕ 完成</string><!--diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xmlnew file mode 100644index 0000000..002ad44--- /dev/null+++ b/app/src/main/res/xml/file_paths.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<paths>+ <cache-path name="shots" path="shots/" />+</paths>