diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 01d980059d..80c9312fe6 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -26,6 +26,7 @@
+
diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt
index ac9995412b..9f74aa4e59 100644
--- a/app/src/main/java/com/droiddeck/launcher/App.kt
+++ b/app/src/main/java/com/droiddeck/launcher/App.kt
@@ -44,6 +44,7 @@ class App : Application() {
CrashHandler.install(this)
com.droiddeck.launcher.agent.AgentHost.refresh(this)
com.droiddeck.launcher.agent.AgentTab.load(this)
+ com.droiddeck.launcher.ui.AgentPet.install(this)
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
com.droiddeck.launcher.lab.LabNotice.started(this)
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
index b2f45bc4ed..26dae4858d 100644
--- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
@@ -84,7 +84,7 @@ import com.droiddeck.launcher.session.SteamLibraries
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays
-class FrontEndActivity : ComponentActivity() {
+class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPetHost {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
@@ -1782,6 +1782,8 @@ class FrontEndActivity : ComponentActivity() {
}, "finish-abandoned").start()
}
+ override val petBlocked: Boolean get() = false
+
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
@@ -1875,6 +1877,7 @@ class FrontEndActivity : ComponentActivity() {
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
+ if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
if (compatLaunch != null) {
if (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
if (event.action == KeyEvent.ACTION_UP) cancelCompatLaunch()
diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
index dc87e93d04..5e7a39b639 100644
--- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
@@ -151,7 +151,7 @@ import com.droiddeck.launcher.ui.sessionDrawerPages
import com.droiddeck.launcher.ui.step
import kotlin.math.abs
-class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
+class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
@@ -159,6 +159,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private lateinit var pip: com.droiddeck.launcher.session.SessionPipController
private var pipUi by mutableStateOf(false)
+
+ override val petBlocked: Boolean get() = drawerOpenState || pipUi || pcKeyboardOpen
private var pipAutoEnter by mutableStateOf(false)
private var unfoldedControls by mutableStateOf(false)
private var unfoldedControlsWithController by mutableStateOf(false)
@@ -2899,6 +2901,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
+ if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
val steamVolume =
diff --git a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt
index 014fc0b4e7..492d626c5b 100644
--- a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt
+++ b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt
@@ -13,7 +13,6 @@ import android.widget.FrameLayout
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
-import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.ui.Motion
import com.droiddeck.launcher.wayland.WaylandCompositor
@@ -38,6 +37,8 @@ class DroidDeckHudHost(context: Context) {
private var snapping = false
private var previewFade: ValueAnimator? = null
private var flingX = 0f
+ private var flingY = 0f
+ private var throwSpring: com.droiddeck.launcher.ui.FlingSpring? = null
private var engine = ""
private var gpuName = ""
private var protonPid = 0
@@ -94,18 +95,22 @@ class DroidDeckHudHost(context: Context) {
stopMotion(hud)
shrinkPastEdge(hud, rawX, rawY)
}
- hud.setOnFlungListener { vx, _ -> flingX = vx }
+ hud.setOnFlungListener { vx, vy -> flingX = vx; flingY = vy }
hud.setOnTabDraggedListener { x, y -> dragTab(hud, x, y) }
hud.setOnTabDroppedListener { dropTab(hud) }
hud.setOnTabDragCancelledListener { snapping = false; keepOnScreen(hud) }
hud.setOnMovedListener { x, y ->
wantX = x; wantY = y
val vx = flingX
+ val vy = flingY
flingX = 0f
- dockEdgeFor(hud)?.let { edge -> setDock(hud, edge); return@setOnMovedListener }
+ flingY = 0f
+ // A throw only carries the strip into its tab; a floating HUD flung across goes to the other side.
+ val coast = hud.isStrip
+ dockEdgeFor(hud, if (coast) vx else 0f, if (coast) vy else 0f)?.let { edge -> setDock(hud, edge); return@setOnMovedListener }
stopMotion(hud)
fadeDockPreview(hud)
- if (snaps && !hud.isStrip) { snapToAnchor(hud, vx); return@setOnMovedListener }
+ if (snaps && !hud.isStrip) { snapToAnchor(hud, vx, vy); return@setOnMovedListener }
val fromX = hud.x; val fromY = hud.y
keepOnScreen(hud)
wantX = hud.x; wantY = hud.y
@@ -178,9 +183,8 @@ class DroidDeckHudHost(context: Context) {
private fun applyShown() {
if (!running) return
val show = !hidden && !backgrounded
- val visible = show && SessionState.mode != SessionService.MODE_DESKTOP
- view?.visibility = if (visible) View.VISIBLE else View.GONE
- showing = visible
+ view?.visibility = if (show) View.VISIBLE else View.GONE
+ showing = show
if (show != polling) {
polling = show
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
@@ -247,23 +251,26 @@ class DroidDeckHudHost(context: Context) {
return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f
}
- private fun dockEdgeFor(v: View): DroidDeckHudDock? {
- val over = overhang(v) ?: return null
+ /** The edge the HUD tucks into: one it hangs far enough over, or would once a throw at [vx], [vy] coasts out. */
+ private fun dockEdgeFor(v: View, vx: Float = 0f, vy: Float = 0f): DroidDeckHudDock? {
+ val over = overhang(v, vx * com.droiddeck.launcher.ui.EdgeFling.COAST_S, vy * com.droiddeck.launcher.ui.EdgeFling.COAST_S) ?: return null
return over.key.takeIf { over.value >= DOCK_OVERHANG }
}
- private fun overhang(v: View): Map.Entry? {
+ private fun overhang(v: View, dx: Float = 0f, dy: Float = 0f): Map.Entry? {
val p = v.parent as? View ?: return null
if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return null
val strip = (v as? DroidDeckHudView)?.isStrip == true
val density = v.resources.displayMetrics.density
val w = if (strip) minOf(v.width.toFloat(), STRIP_PULL_ACROSS_DP * density) else v.width.toFloat()
val h = if (strip) maxOf(v.height.toFloat(), STRIP_PULL_OFF_DP * density) else v.height.toFloat()
+ val x = v.x + dx
+ val y = v.y + dy
return mapOf(
- DroidDeckHudDock.LEFT to -v.x / w,
- DroidDeckHudDock.RIGHT to (v.x + v.width - p.width) / w,
- DroidDeckHudDock.TOP to -v.y / h,
- DroidDeckHudDock.BOTTOM to (v.y + v.height - p.height) / h,
+ DroidDeckHudDock.LEFT to -x / w,
+ DroidDeckHudDock.RIGHT to (x + v.width - p.width) / w,
+ DroidDeckHudDock.TOP to -y / h,
+ DroidDeckHudDock.BOTTOM to (y + v.height - p.height) / h,
).maxByOrNull { it.value }
}
@@ -298,6 +305,7 @@ class DroidDeckHudHost(context: Context) {
}
private fun stopMotion(hud: DroidDeckHudView) {
+ throwSpring?.cancel()
hud.animate().setUpdateListener(null)
hud.animate().cancel()
}
@@ -327,23 +335,21 @@ class DroidDeckHudHost(context: Context) {
}
}
- private fun snapToAnchor(hud: DroidDeckHudView, vx: Float) {
+ /** Sends the HUD to a side the way a chat head goes: by where the throw would carry it, springing on from its speed. */
+ private fun snapToAnchor(hud: DroidDeckHudView, vx: Float, vy: Float) {
val p = hud.parent as? View ?: return
val maxX = (p.width - hud.width).toFloat().coerceAtLeast(0f)
val maxY = (p.height - hud.height).toFloat().coerceAtLeast(0f)
- anchorX = if (hud.x + vx * FLING_REACH_S < maxX / 2f) 0f else 1f
+ val right = com.droiddeck.launcher.ui.EdgeFling.toRight(hud.x + hud.width / 2f, p.width.toFloat(), vx, context.resources.displayMetrics.density)
+ anchorX = if (right) 1f else 0f
wantX = anchorX * maxX
- wantY = hud.y.coerceIn(0f, maxY)
+ wantY = com.droiddeck.launcher.ui.EdgeFling.restY(hud.y, vy, 0f, maxY)
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
stopMotion(hud)
- if (Motion.scale == 0f) {
- hud.scaleX = 1f; hud.scaleY = 1f
- hud.x = wantX; hud.y = wantY
- return
- }
+ hud.scaleX = 1f; hud.scaleY = 1f
snapping = true
- hud.animate().x(wantX).y(wantY).scaleX(1f).scaleY(1f).setDuration(Motion.ms(260).toLong()).setInterpolator(EASE)
- .withEndAction { snapping = false; keepOnScreen(hud) }.start()
+ val spring = throwSpring ?: com.droiddeck.launcher.ui.FlingSpring { sx, sy -> hud.x = sx; hud.y = sy }.also { throwSpring = it }
+ spring.start(hud.x, hud.y, vx, vy, wantX, wantY) { snapping = false; keepOnScreen(hud) }
}
private fun shrinkPastEdge(hud: DroidDeckHudView, rawX: Float, rawY: Float) {
@@ -500,10 +506,9 @@ class DroidDeckHudHost(context: Context) {
companion object {
private const val DOCK_OVERHANG = 0.4f
- private const val FLING_REACH_S = 0.18f
private const val PREVIEW_FROM = 0.55f
- private const val STRIP_PULL_ACROSS_DP = 600f
- private const val STRIP_PULL_OFF_DP = 150f
+ private const val STRIP_PULL_ACROSS_DP = 360f
+ private const val STRIP_PULL_OFF_DP = 100f
private const val EXPAND_FADE = 0.5f
private val EASE = PathInterpolator(0.2f, 0.8f, 0.2f, 1f)
diff --git a/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java b/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java
index 98c34df7ce..b4c1cfc7ea 100644
--- a/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java
+++ b/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java
@@ -50,6 +50,7 @@ public class HudLockController {
private final Callbacks cb;
private final GestureDetector detector;
private final ScaleGestureDetector scaleDetector;
+ private final android.view.VelocityTracker velocity = android.view.VelocityTracker.obtain();
private boolean locked = false;
@@ -86,8 +87,18 @@ public class HudLockController {
public boolean onTouchEvent(MotionEvent event) {
scaleDetector.onTouchEvent(event);
detector.onTouchEvent(event);
+ // The HUD moves under the finger, so the throw is measured on the screen, not in the HUD.
+ MotionEvent onScreen = MotionEvent.obtain(event);
+ onScreen.setLocation(event.getRawX(), event.getRawY());
+ if (event.getActionMasked() == MotionEvent.ACTION_DOWN) velocity.clear();
+ velocity.addMovement(onScreen);
+ onScreen.recycle();
int action = event.getActionMasked();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
+ if (dragging && !locked && !pinched && action == MotionEvent.ACTION_UP) {
+ velocity.computeCurrentVelocity(1000);
+ cb.onFlung(velocity.getXVelocity(), velocity.getYVelocity());
+ }
if (dragging && !locked) cb.onMoved(view.getX(), view.getY());
dragging = false;
}
@@ -124,12 +135,6 @@ public class HudLockController {
return true;
}
- @Override
- public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
- if (dragging && !locked && !pinched) cb.onFlung(velocityX, velocityY);
- return true;
- }
-
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (pinched) return true;
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt
index 868cf4fbf0..ed036a4933 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt
@@ -51,6 +51,7 @@ import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material.icons.outlined.History
import androidx.compose.material.icons.outlined.Memory
import androidx.compose.material.icons.outlined.MoreHoriz
+import androidx.compose.material.icons.outlined.Pets
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Stop
import androidx.compose.material3.CircularProgressIndicator
@@ -127,7 +128,7 @@ private const val COMPOSER_SLIDE_MS = 350L
*/
@Composable
internal fun AgentPage(
- modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true, startTyping: Boolean = true,
+ modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true, startTyping: Boolean = true, hidesPet: Boolean = true,
) {
val context = LocalContext.current
val view = LocalView.current
@@ -143,6 +144,11 @@ internal fun AgentPage(
}
remember { AgentHost.refresh(context) }
LaunchedEffect(AgentHost.unseen, visible) { if (visible) AgentHost.seen() }
+ DisposableEffect(visible, hidesPet) {
+ val counts = visible && hidesPet
+ if (counts) AgentPet.agentOnScreen++
+ onDispose { if (counts) AgentPet.agentOnScreen-- }
+ }
remember { AgentSetup.check(context) }
var setup by rememberSaveable { mutableStateOf(false) }
val draft = rememberSaveable { mutableStateOf("") }
@@ -631,6 +637,9 @@ private fun AgentEditor(
menu = false
AgentHost.forget(context)
}
+ HeaderAction(Icons.Outlined.Pets, stringResource(R.string.setup_agent_pet), selected = AgentPet.enabled, size = 32.dp, tag = "agent-pet-toggle") {
+ AgentPet.set(context, !AgentPet.enabled)
+ }
HeaderAction(Icons.Outlined.Settings, stringResource(R.string.agent_setup_title), enabled = !working, size = 32.dp, tag = "agent-settings") {
menu = false
onSetup()
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt
new file mode 100644
index 0000000000..f154295450
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt
@@ -0,0 +1,319 @@
+package com.droiddeck.launcher.ui
+
+import android.app.Activity
+import android.app.Application
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.os.Bundle
+import android.os.Handler
+import android.os.Looper
+import android.os.SystemClock
+import android.provider.Settings
+import android.view.View
+import android.view.ViewGroup
+import android.widget.FrameLayout
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.gestures.detectDragGestures
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableLongStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.snapshotFlow
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.platform.ComposeView
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.platform.testTag
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.onClick
+import androidx.compose.ui.semantics.role
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.IntSize
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import com.droiddeck.launcher.agent.AgentHost
+import kotlinx.coroutines.MainScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlin.math.roundToInt
+
+/** A DroidDeck window the pet can live in when it may not float over other apps. */
+internal interface AgentPetHost {
+ /** Something already covers the pet's place, such as the session drawer. */
+ val petBlocked: Boolean
+}
+
+/**
+ * DeeDee, the agent's pet: shows what the agent is doing and opens a chat with it. With the
+ * "display over other apps" permission it floats over every app in windows of its own
+ * ([PetWindows]); without it, it lives in DroidDeck's own windows. Either way it opens the same
+ * chat, growing out of it.
+ */
+internal object AgentPet {
+ var enabled by mutableStateOf(false)
+ private set
+ /** May draw over other apps. */
+ var allowed by mutableStateOf(false)
+ private set
+ /** Agent pages on screen; the pet steps aside while the conversation itself is in view. */
+ var agentOnScreen by mutableIntStateOf(0)
+ var now by mutableLongStateOf(SystemClock.elapsedRealtime())
+ private set
+ /** When the agent last changed what it was doing. */
+ var since by mutableLongStateOf(SystemClock.elapsedRealtime())
+ private set
+ /** The floating windows could not be made, so the pet stays in DroidDeck's own windows instead. */
+ private var floatFailed by mutableStateOf(false)
+ val floating get() = enabled && allowed && !floatFailed
+ /** How to close the chat open inside each DroidDeck window that has one. */
+ private val closeInWindow = java.util.WeakHashMap Unit>()
+
+ /**
+ * B and Back close a chat open inside [host] before the window acts on them, since the window's
+ * own keys (leaving a session, going back a page) would otherwise run under it.
+ */
+ fun handleBack(host: AgentPetHost, event: android.view.KeyEvent): Boolean {
+ val close = closeInWindow[host] ?: return false
+ if (event.keyCode != android.view.KeyEvent.KEYCODE_BACK && event.keyCode != android.view.KeyEvent.KEYCODE_BUTTON_B) return false
+ if (event.action == android.view.KeyEvent.ACTION_UP) close()
+ return true
+ }
+
+ internal fun chatOpenInWindow(host: AgentPetHost, close: (() -> Unit)?) {
+ if (close == null) closeInWindow.remove(host) else closeInWindow[host] = close
+ }
+ private var windows: PetWindows? = null
+ private val main = Handler(Looper.getMainLooper())
+ private const val TAG = "agent-pet"
+ private const val KEY = "pet"
+ private const val SIDE = "pet_side"
+ private const val HEIGHT = "pet_y"
+
+ fun set(context: Context, on: Boolean) {
+ enabled = on
+ AgentHost.prefs(context).edit().putBoolean(KEY, on).apply()
+ }
+
+ /** Opens the system page where the user lets DroidDeck draw over other apps. */
+ fun requestFloating(context: Context) {
+ val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}"))
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ runCatching { context.startActivity(intent) }
+ }
+
+ internal fun place(context: Context) = AgentHost.prefs(context).let { it.getBoolean(SIDE, true) to it.getFloat(HEIGHT, 0.3f) }
+
+ internal fun save(context: Context, right: Boolean, height: Float) {
+ AgentHost.prefs(context).edit().putBoolean(SIDE, right).putFloat(HEIGHT, height).apply()
+ }
+
+ fun install(app: Application) {
+ enabled = AgentHost.prefs(app).getBoolean(KEY, false)
+ allowed = PetWindows.allowed(app)
+ val scope = MainScope()
+ scope.launch {
+ snapshotFlow { Triple(AgentHost.state, AgentHost.entries.size, AgentHost.lab?.running) }.collect { since = SystemClock.elapsedRealtime() }
+ }
+ scope.launch {
+ snapshotFlow { floating && AgentHost.installed }.collect { show ->
+ if (show && windows == null) windows = runCatching { PetWindows(app) }.onFailure {
+ android.util.Log.w("AgentPet", "could not float the pet", it)
+ floatFailed = true
+ }.getOrNull()
+ if (!show) windows?.close()?.also { windows = null }
+ }
+ }
+ tick(app)
+ app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
+ override fun onActivityResumed(activity: Activity) {
+ allowed = PetWindows.allowed(activity)
+ attach(activity)
+ }
+ override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
+ override fun onActivityStarted(activity: Activity) = Unit
+ override fun onActivityPaused(activity: Activity) = Unit
+ override fun onActivityStopped(activity: Activity) = Unit
+ override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
+ override fun onActivityDestroyed(activity: Activity) = Unit
+ })
+ }
+
+ private fun tick(app: Application) {
+ now = SystemClock.elapsedRealtime()
+ // The permission can be granted or taken back in Settings while DroidDeck is away.
+ if (enabled) allowed = PetWindows.allowed(app)
+ main.postDelayed({ tick(app) }, 1_000)
+ }
+
+ private fun attach(activity: Activity) {
+ val host = activity as? AgentPetHost ?: return
+ val decor = activity.window.decorView as? ViewGroup ?: return
+ if (decor.findViewWithTag(TAG) != null) return
+ val layer = ComposeView(activity).apply {
+ tag = TAG
+ isFocusable = false
+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
+ setContent { DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(activity)) { PetLayer(host) } }
+ }
+ decor.addView(layer, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
+ }
+}
+
+private const val SLEEP_AFTER_MS = 5 * 60_000L
+private const val CHEER_MS = 10_000L
+internal const val PREVIEW_MS = 6_000L
+
+/** What the agent is up to, as the pet shows it; [since] is when the agent last changed what it was doing. */
+internal fun petState(now: Long, since: Long): PetState {
+ if (AgentHost.state == AgentHost.State.WORKING || AgentHost.lab?.running == true) return PetState.WORKING
+ val last = AgentHost.entries.lastOrNull { it is AgentHost.Entry.Finished } as? AgentHost.Entry.Finished
+ if (AgentHost.unseen && last != null && !last.stopped) {
+ if (last.error != null) return PetState.ERROR
+ val said = (AgentHost.entries.lastOrNull { it is AgentHost.Entry.Said } as? AgentHost.Entry.Said)?.text?.trimEnd().orEmpty()
+ if (last.planned || said.endsWith("?")) return PetState.QUESTION
+ if (now - since < CHEER_MS) return PetState.DONE
+ }
+ return if (now - since > SLEEP_AFTER_MS) PetState.SLEEP else PetState.IDLE
+}
+
+internal fun petStateNow() = petState(AgentPet.now, AgentPet.since)
+
+/** The line the preview bubble shows while the pet has news, or null when it has none. */
+internal fun petBubbleText(): String? {
+ if (!AgentHost.unseen) return null
+ val state = petStateNow()
+ if (state != PetState.DONE && state != PetState.QUESTION && state != PetState.ERROR) return null
+ val last = AgentHost.entries.lastOrNull { it is AgentHost.Entry.Finished } as? AgentHost.Entry.Finished
+ last?.error?.let { return it }
+ val said = AgentHost.entries.lastOrNull { it is AgentHost.Entry.Said } as? AgentHost.Entry.Said ?: return null
+ return said.text.lineSequence().map { it.trim().trimStart('#', '*', '-', ' ') }.firstOrNull { it.isNotEmpty() }
+}
+
+/** DeeDee in [state], with a dot while a reply waits to be read. */
+@Composable
+internal fun PetFigure(state: PetState, modifier: Modifier) {
+ Box(modifier.testTag("agent-pet")) {
+ Box(Modifier.fillMaxSize().padding(4.dp).clip(CircleShape).background(Color(0xEB0E141B)).border(1.dp, Color(0x29FFFFFF), CircleShape))
+ DeeDee(state, Modifier.fillMaxSize().padding(6.dp))
+ if (AgentHost.unseen && (state == PetState.IDLE || state == PetState.SLEEP)) Box(
+ Modifier.align(Alignment.TopEnd).padding(8.dp).size(14.dp).clip(CircleShape).background(Color(0xFF1A9FFF)).border(2.dp, Color(0xFF0E141B), CircleShape),
+ )
+ }
+}
+
+@Composable
+internal fun PetPreview(text: String, modifier: Modifier, onTap: () -> Unit) {
+ val shape = RoundedCornerShape(16.dp)
+ Text(
+ text, fontSize = 14.sp, color = Color.White, maxLines = 2, overflow = TextOverflow.Ellipsis,
+ modifier = modifier.widthIn(max = 260.dp).clip(shape).background(Color(0xF0171D25)).border(1.dp, Color(0x33FFFFFF), shape)
+ .pointerInput(Unit) { detectTapGestures { onTap() } }.padding(horizontal = 14.dp, vertical = 10.dp),
+ )
+}
+
+/** The pet inside one DroidDeck window, for when it may not float over other apps. */
+@Composable
+private fun PetLayer(host: AgentPetHost) {
+ var chatOpen by remember { mutableStateOf(false) }
+ var chatShown by remember { mutableStateOf(false) }
+ val shown = AgentPet.enabled && !AgentPet.floating && AgentHost.installed && (chatShown || AgentPet.agentOnScreen == 0) && !host.petBlocked
+ if (!shown) return
+ val context = LocalContext.current
+ val motion = remember { PetMotion(context) }
+ val density = LocalDensity.current
+ val openLabel = androidx.compose.ui.res.stringResource(com.droiddeck.launcher.R.string.agent_pet_open)
+ val openChat = {
+ motion.dock()
+ chatShown = true
+ chatOpen = true
+ }
+ val closeChat = {
+ chatOpen = false
+ motion.undock()
+ }
+ BoxWithConstraints(Modifier.fillMaxSize()) {
+ motion.fit(constraints.maxWidth.toFloat(), constraints.maxHeight.toFloat())
+ if (chatShown) PetChat(chatOpen, motion, closeChat) { chatShown = false }
+ androidx.compose.runtime.DisposableEffect(host, chatOpen) {
+ AgentPet.chatOpenInWindow(host, if (chatOpen) closeChat else null)
+ onDispose { AgentPet.chatOpenInWindow(host, null) }
+ }
+ var bubble by remember { mutableStateOf(null) }
+ val news = petBubbleText()
+ LaunchedEffect(news) {
+ bubble = news
+ if (news != null) {
+ delay(PREVIEW_MS)
+ bubble = null
+ }
+ }
+ if (motion.dragging) Box(Modifier.offset {
+ val (tx, ty) = motion.target
+ IntOffset((tx - motion.size / 2).roundToInt(), (ty - motion.size / 2).roundToInt())
+ }) { PetCloseTarget(motion.overTarget) }
+ val text = bubble
+ if (text != null && !motion.dragging) {
+ var size by remember { mutableStateOf(IntSize.Zero) }
+ val gap = with(density) { 10.dp.toPx() }
+ PetPreview(text, Modifier.onSizeChanged { size = it }.offset {
+ val x = if (motion.right) motion.x - gap - size.width else motion.x + motion.size + gap
+ IntOffset(x.roundToInt(), (motion.y + motion.size / 2 - size.height / 2).roundToInt())
+ }) {
+ bubble = null
+ openChat()
+ }
+ }
+ PetFigure(
+ petStateNow(),
+ Modifier.offset { IntOffset(motion.x.roundToInt(), motion.y.roundToInt()) }
+ .size(with(density) { motion.size.toDp() })
+ .semantics {
+ contentDescription = openLabel
+ role = androidx.compose.ui.semantics.Role.Button
+ onClick { if (chatOpen) closeChat() else openChat(); true }
+ }
+ .pointerInput(Unit) { detectTapGestures { bubble = null; if (chatOpen) closeChat() else openChat() } }
+ .pointerInput(Unit) {
+ // The pet moves under the finger, so its velocity is measured where it is on the screen.
+ val tracker = androidx.compose.ui.input.pointer.util.VelocityTracker()
+ detectDragGestures(
+ onDragStart = { bubble = null; if (chatOpen) closeChat(); tracker.resetTracking(); motion.start() },
+ onDrag = { change, amount ->
+ change.consume()
+ motion.move(amount.x, amount.y)
+ tracker.addPosition(change.uptimeMillis, androidx.compose.ui.geometry.Offset(motion.x + change.position.x, motion.y + change.position.y))
+ },
+ onDragEnd = {
+ val v = tracker.calculateVelocity()
+ if (motion.end(v.x, v.y)) AgentPet.set(context, false)
+ },
+ onDragCancel = { motion.cancel() },
+ )
+ },
+ )
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt
new file mode 100644
index 0000000000..c8d3aba8c9
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt
@@ -0,0 +1,559 @@
+package com.droiddeck.launcher.ui
+
+import android.animation.ValueAnimator
+import android.annotation.SuppressLint
+import android.content.Context
+import android.graphics.PixelFormat
+import android.os.Build
+import android.provider.Settings
+import android.view.Gravity
+import android.view.KeyEvent
+import android.view.MotionEvent
+import android.view.View
+import android.view.ViewConfiguration
+import android.view.WindowManager
+import android.view.animation.OvershootInterpolator
+import android.widget.FrameLayout
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.width
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.Close
+import androidx.compose.material3.Icon
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.snapshotFlow
+import androidx.compose.animation.core.Animatable
+import androidx.compose.foundation.Canvas
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.unit.IntOffset
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.input.key.onPreviewKeyEvent
+import androidx.compose.ui.platform.ComposeView
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleOwner
+import androidx.lifecycle.LifecycleRegistry
+import androidx.lifecycle.setViewTreeLifecycleOwner
+import androidx.savedstate.SavedStateRegistry
+import androidx.savedstate.SavedStateRegistryController
+import androidx.savedstate.SavedStateRegistryOwner
+import androidx.savedstate.setViewTreeSavedStateRegistryOwner
+import com.droiddeck.launcher.R
+import com.droiddeck.launcher.agent.AgentHost
+import kotlinx.coroutines.MainScope
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.launch
+import kotlin.math.abs
+import kotlin.math.hypot
+import kotlin.math.roundToInt
+
+/**
+ * Where the pet is on the screen and how it moves: dragged anywhere, then settling against the
+ * nearer side edge, or dropped on the close target to turn it off. While its chat is open it is
+ * docked at the top corner, the way a chat head hops up when its conversation opens, and goes home
+ * when the chat closes. Positions are screen pixels.
+ */
+internal class PetMotion(private val context: Context) {
+ var x by mutableFloatStateOf(0f)
+ private set
+ var y by mutableFloatStateOf(0f)
+ private set
+ var right by mutableStateOf(true)
+ private set
+ var dragging by mutableStateOf(false)
+ private set
+ var width by mutableFloatStateOf(0f)
+ private set
+ var height by mutableFloatStateOf(0f)
+ private set
+ /** Docked for the chat; where to go back to is kept as a side and a relative height. */
+ var docked by mutableStateOf(false)
+ private set
+ private val density = context.resources.displayMetrics.density
+ val size = 76 * density
+ private val margin = 6 * density
+ private val inset = 24 * density
+ private var settle: ValueAnimator? = null
+ private val spring = FlingSpring { sx, sy -> x = sx; y = sy }
+
+ val dockX get() = width - size - margin
+
+ private companion object {
+ /** The share of the pet that hangs past the edge it rests against. */
+ const val TUCK = 0.2f
+ }
+ val dockY get() = inset
+ val target get() = Pair(width / 2, height - 72 * density)
+ val overTarget get() = dragging && hypot(x + size / 2 - target.first, y + size / 2 - target.second) < size
+
+ /** Fits the pet into a [w] by [h] screen, keeping its side and relative height, as after a rotation. */
+ fun fit(w: Float, h: Float) {
+ if (w <= 0 || h <= 0 || (w == width && h == height)) return
+ val first = width == 0f
+ val fraction = if (first) AgentPet.place(context).also { right = it.first }.second else if (docked) home else fractionOf(y)
+ settle?.cancel()
+ spring.cancel()
+ width = w
+ height = h
+ home = fraction
+ if (docked) {
+ x = dockX
+ y = dockY
+ } else {
+ x = edge(right)
+ y = inset + travel() * fraction
+ }
+ }
+
+ private var home = 0f
+ private fun travel() = (height - size - inset * 2).coerceAtLeast(0f)
+ private fun fractionOf(at: Float) = if (travel() > 0) ((at - inset) / travel()).coerceIn(0f, 1f) else 0f
+ /** At rest the pet tucks part of itself past the screen edge, as a chat head does. */
+ private fun edge(side: Boolean) = if (side) width - size * (1f - TUCK) else -size * TUCK
+
+ /** Hops up to the top corner for the chat. */
+ fun dock() {
+ if (docked) return
+ home = fractionOf(y)
+ docked = true
+ glide(dockX, dockY, 260, OvershootInterpolator(0.9f))
+ }
+
+ /** Goes back to where it was before the chat opened. */
+ fun undock() {
+ if (!docked) return
+ docked = false
+ glide(edge(right), inset + travel() * home, 320, android.view.animation.DecelerateInterpolator(1.6f))
+ }
+
+ fun start() {
+ settle?.cancel()
+ spring.cancel()
+ docked = false
+ dragging = true
+ }
+
+ fun move(dx: Float, dy: Float) {
+ x += dx
+ y += dy
+ }
+
+ /** A drag the system took away: the pet goes back to an edge, never to the close target. */
+ fun cancel() {
+ if (!dragging) return
+ dragging = false
+ right = x + size / 2 > width / 2
+ val toY = y.coerceIn(inset, (height - size - inset).coerceAtLeast(inset))
+ home = fractionOf(toY)
+ spring.start(x, y, 0f, 0f, edge(right), toY)
+ }
+
+ /** Ends a drag let go at [vx], [vy] pixels per second; true when the pet was dropped on the close target. */
+ fun end(vx: Float = 0f, vy: Float = 0f): Boolean {
+ val dismissed = overTarget
+ dragging = false
+ if (dismissed) return true
+ right = EdgeFling.toRight(x + size / 2, width, vx, density)
+ val toY = EdgeFling.restY(y, vy, inset, height - size - inset)
+ home = fractionOf(toY)
+ AgentPet.save(context, right, home)
+ spring.start(x, y, vx, vy, edge(right), toY)
+ return false
+ }
+
+ private fun glide(toX: Float, toY: Float, ms: Long, curve: android.animation.TimeInterpolator) {
+ settle?.cancel()
+ spring.cancel()
+ val fromX = x
+ val fromY = y
+ settle = ValueAnimator.ofFloat(0f, 1f).apply {
+ duration = (ms * Motion.scale).toLong().coerceAtLeast(0)
+ interpolator = curve
+ addUpdateListener {
+ val f = it.animatedValue as Float
+ x = fromX + (toX - fromX) * f
+ y = fromY + (toY - fromY) * f
+ }
+ start()
+ }
+ }
+}
+
+/** Lets a ComposeView live in a window no activity owns. */
+private class OverlayOwner : LifecycleOwner, SavedStateRegistryOwner {
+ private val registry = LifecycleRegistry(this)
+ private val saved = SavedStateRegistryController.create(this)
+ override val lifecycle: Lifecycle get() = registry
+ override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
+
+ init {
+ saved.performRestore(null)
+ registry.currentState = Lifecycle.State.RESUMED
+ }
+
+ fun destroy() {
+ registry.currentState = Lifecycle.State.DESTROYED
+ }
+}
+
+/**
+ * The pet over every app, in windows of its own: the pet, its message preview, the close target
+ * while it is dragged, and the chat it opens. Needs the "display over other apps" permission.
+ */
+@SuppressLint("ClickableViewAccessibility")
+internal class PetWindows(private val context: Context) {
+ private val windows = context.getSystemService(WindowManager::class.java)
+ private val owner = OverlayOwner()
+ private val motion = PetMotion(context)
+ private val scope = MainScope()
+ /** The chat is open, or opening; its window stays up until it has shrunk back into the pet. */
+ private var chatOpen by mutableStateOf(false)
+ private var bubble by mutableStateOf(null)
+ private var bubbleWidth by mutableFloatStateOf(0f)
+ private var bubbleHeight by mutableFloatStateOf(0f)
+ /** The windows are in the window manager, so moving one goes through it. */
+ private var added = false
+ private val turns = object : android.content.ComponentCallbacks {
+ override fun onConfigurationChanged(newConfig: android.content.res.Configuration) = fitScreen()
+ @Deprecated("Deprecated in Java")
+ override fun onLowMemory() = Unit
+ }
+
+ // A window emptied to no size keeps showing its last frame, so each is hidden as a whole instead.
+ private val head = window(touchable = true, focusable = false) {
+ PetFigure(petStateNow(), Modifier.size(76.dp))
+ }
+ private val preview = window(touchable = true, focusable = false, onSize = { w, h -> bubbleWidth = w.toFloat(); bubbleHeight = h.toFloat() }) {
+ bubble?.let { PetPreview(it, Modifier.padding(2.dp)) { openChat() } }
+ }
+ private val target = window(touchable = false, focusable = false) {
+ PetCloseTarget(motion.overTarget)
+ }
+ private val chat: Window = window(touchable = true, focusable = true, full = true) {
+ PetChat(chatOpen, motion, ::closeChat) { showChat(false) }
+ }
+
+ init {
+ head.view.setOnTouchListener(DragTouch())
+ head.view.contentDescription = context.getString(R.string.agent_pet_open)
+ head.view.setOnClickListener { if (chatOpen) closeChat() else openChat() }
+ scope.launch { snapshotFlow { Triple(motion.x, motion.y, motion.right) }.collectLatest { place() } }
+ scope.launch { snapshotFlow { bubbleWidth to bubbleHeight }.collectLatest { place() } }
+ scope.launch { snapshotFlow { AgentPet.agentOnScreen == 0 }.collectLatest { setVisible(head, it) } }
+ scope.launch { snapshotFlow { motion.dragging }.collectLatest { setVisible(target, it) } }
+ scope.launch {
+ snapshotFlow { bubble != null && !chatOpen && !motion.dragging && AgentPet.agentOnScreen == 0 }.collectLatest { setVisible(preview, it) }
+ }
+ scope.launch {
+ snapshotFlow { petBubbleText() }.collectLatest { text ->
+ bubble = text
+ if (text != null) {
+ kotlinx.coroutines.delay(PREVIEW_MS)
+ bubble = null
+ }
+ }
+ }
+ fitScreen()
+ context.registerComponentCallbacks(turns)
+ place()
+ listOf(target, preview).forEach { setVisible(it, false) }
+ showChat(false)
+ listOf(chat, target, preview, head).forEach { windows.addView(it.view, it.params) }
+ added = true
+ }
+
+ private class Window(val view: FrameLayout, val params: WindowManager.LayoutParams, val touchable: Boolean)
+
+ private fun window(
+ touchable: Boolean, focusable: Boolean, full: Boolean = false, onSize: ((Int, Int) -> Unit)? = null, content: @Composable () -> Unit,
+ ): Window {
+ val compose = ComposeView(context).apply {
+ setViewTreeLifecycleOwner(owner)
+ setViewTreeSavedStateRegistryOwner(owner)
+ setContent { DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(context)) { content() } }
+ }
+ val frame = object : FrameLayout(context) {
+ override fun dispatchKeyEvent(event: KeyEvent): Boolean {
+ if (full && event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP && chatOpen) {
+ closeChat()
+ return true
+ }
+ return super.dispatchKeyEvent(event)
+ }
+ }.apply {
+ addView(compose)
+ setViewTreeLifecycleOwner(owner)
+ setViewTreeSavedStateRegistryOwner(owner)
+ }
+ val size = if (full) WindowManager.LayoutParams.MATCH_PARENT else WindowManager.LayoutParams.WRAP_CONTENT
+ val params = WindowManager.LayoutParams(
+ size, size, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
+ (if (focusable) 0 else WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) or
+ (if (touchable) 0 else WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE) or
+ WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
+ (if (full) 0 else WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS),
+ PixelFormat.TRANSLUCENT,
+ ).apply {
+ gravity = Gravity.TOP or Gravity.START
+ if (full) softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
+ }
+ if (onSize != null) compose.addOnLayoutChangeListener { v, _, _, _, _, _, _, _, _ -> onSize(v.width, v.height) }
+ return Window(frame, params, touchable)
+ }
+
+ /** A hidden overlay window still owns its frame, which the system can stretch over the screen, so it also stops taking touches. */
+ private fun setVisible(window: Window, shown: Boolean) {
+ window.view.visibility = if (shown) View.VISIBLE else View.GONE
+ setTouchable(window, shown && window.touchable)
+ }
+
+ private fun setTouchable(window: Window, on: Boolean) {
+ val flags = if (on) window.params.flags and WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE.inv()
+ else window.params.flags or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
+ if (flags == window.params.flags) return
+ window.params.flags = flags
+ if (added) runCatching { windows.updateViewLayout(window.view, window.params) }
+ }
+
+ private fun place() {
+ val gap = 10 * context.resources.displayMetrics.density
+ update(head, motion.x, motion.y)
+ val bx = if (motion.right) motion.x - gap - bubbleWidth else motion.x + motion.size + gap
+ update(preview, bx, motion.y + motion.size / 2 - bubbleHeight / 2)
+ val (tx, ty) = motion.target
+ update(target, tx - motion.size / 2, ty - motion.size / 2)
+ }
+
+ private fun update(window: Window, x: Float, y: Float) {
+ if (window.params.x == x.roundToInt() && window.params.y == y.roundToInt()) return
+ window.params.x = x.roundToInt()
+ window.params.y = y.roundToInt()
+ if (added) runCatching { windows.updateViewLayout(window.view, window.params) }
+ }
+
+ private fun openChat() {
+ bubble = null
+ if (chatOpen) return
+ motion.dock()
+ showChat(true)
+ chatOpen = true
+ }
+
+ private fun closeChat() {
+ if (!chatOpen) return
+ chatOpen = false
+ motion.undock()
+ }
+
+ /**
+ * The chat window is always drawn; closed, it waits off the screen and takes neither touches nor
+ * keys, so opening it is a move and not a first layout.
+ */
+ private fun showChat(on: Boolean) {
+ chat.params.x = if (on) 0 else OFFSCREEN
+ val quiet = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
+ chat.params.flags = if (on) chat.params.flags and quiet.inv() else chat.params.flags or quiet
+ if (added) runCatching { windows.updateViewLayout(chat.view, chat.params) }
+ }
+
+ /** The whole screen, the status and navigation bars included, since overlay windows can cover them. */
+ private fun fitScreen() {
+ val bounds = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) windows.maximumWindowMetrics.bounds
+ else android.graphics.Point().also { @Suppress("DEPRECATION") windows.defaultDisplay.getRealSize(it) }.let { android.graphics.Rect(0, 0, it.x, it.y) }
+ motion.fit(bounds.width().toFloat(), bounds.height().toFloat())
+ }
+
+ fun close() {
+ runCatching { context.unregisterComponentCallbacks(turns) }
+ scope.cancel()
+ listOf(head, preview, target, chat).forEach { runCatching { windows.removeView(it.view) } }
+ owner.destroy()
+ }
+
+ /** Drags and taps on the pet, in screen coordinates, since its window moves under the finger. */
+ private inner class DragTouch : View.OnTouchListener {
+ private val slop = ViewConfiguration.get(context).scaledTouchSlop
+ private var downX = 0f
+ private var downY = 0f
+ private var lastX = 0f
+ private var lastY = 0f
+ private var moved = false
+ private var tracker: android.view.VelocityTracker? = null
+
+ /** The window moves under the finger, so velocity is measured on the screen. */
+ private fun track(e: MotionEvent) {
+ val onScreen = MotionEvent.obtain(e).apply { setLocation(e.rawX, e.rawY) }
+ (tracker ?: android.view.VelocityTracker.obtain().also { tracker = it }).addMovement(onScreen)
+ onScreen.recycle()
+ }
+
+ private fun release(): Pair {
+ val t = tracker ?: return 0f to 0f
+ t.computeCurrentVelocity(1000)
+ val v = t.xVelocity to t.yVelocity
+ t.recycle()
+ tracker = null
+ return v
+ }
+
+ override fun onTouch(v: View, e: MotionEvent): Boolean {
+ track(e)
+ when (e.actionMasked) {
+ MotionEvent.ACTION_DOWN -> {
+ downX = e.rawX; downY = e.rawY; lastX = e.rawX; lastY = e.rawY
+ moved = false
+ }
+ MotionEvent.ACTION_MOVE -> {
+ if (!moved && (abs(e.rawX - downX) > slop || abs(e.rawY - downY) > slop)) {
+ moved = true
+ bubble = null
+ closeChat()
+ motion.start()
+ }
+ if (moved) motion.move(e.rawX - lastX, e.rawY - lastY)
+ lastX = e.rawX; lastY = e.rawY
+ }
+ MotionEvent.ACTION_UP -> {
+ val (vx, vy) = release()
+ if (moved) {
+ if (motion.end(vx, vy)) AgentPet.set(context, false)
+ } else v.performClick()
+ }
+ MotionEvent.ACTION_CANCEL -> {
+ release()
+ if (moved) motion.cancel()
+ }
+ }
+ return true
+ }
+ }
+
+ companion object {
+ private const val OFFSCREEN = 10_000
+ fun allowed(context: Context) = Settings.canDrawOverlays(context)
+ }
+}
+
+/**
+ * The floating chat, opened the way a chat head opens its conversation: the pet hops into the top
+ * corner while the whole conversation scales up out of it and fades in, and closing shrinks it back
+ * into the pet as the pet glides home. In landscape it sits beside the docked pet, in portrait
+ * under it. Its contents are built while it is closed, so opening only animates.
+ */
+@Composable
+internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onClosed: () -> Unit) {
+ val colors = MaterialTheme.colorScheme
+ val pal = LocalPalette.current
+ val density = androidx.compose.ui.platform.LocalDensity.current
+ BoxWithConstraints(
+ Modifier.fillMaxSize().onPreviewKeyEvent { e ->
+ val k = e.nativeKeyEvent
+ if (k.keyCode != KeyEvent.KEYCODE_BUTTON_B || k.action != KeyEvent.ACTION_UP) return@onPreviewKeyEvent false
+ onClose()
+ true
+ },
+ ) {
+ val w = constraints.maxWidth.toFloat()
+ val h = constraints.maxHeight.toFloat()
+ val margin = with(density) { 8.dp.toPx() }
+ val gap = with(density) { 6.dp.toPx() }
+ val wide = w > h
+ val panel = if (wide) {
+ val right = motion.dockX - gap
+ Rect((right - with(density) { 900.dp.toPx() }).coerceAtLeast(margin), motion.dockY, right, h - margin)
+ } else {
+ Rect(margin, motion.dockY + motion.size + gap, w - margin, h - margin)
+ }
+ val grow = remember { Animatable(0f) }
+ val fade = remember { Animatable(0f) }
+ LaunchedEffect(open) {
+ if (open) coroutineScope {
+ launch { grow.animateTo(1f, Motion.sp(0.82f, 520f)) }
+ launch { fade.animateTo(1f, Motion.tw(140)) }
+ } else if (fade.value > 0f) {
+ coroutineScope {
+ launch { grow.animateTo(0f, Motion.tw(170, easing = androidx.compose.animation.core.FastOutLinearInEasing)) }
+ launch { delay(Motion.ms(40).toLong()); fade.animateTo(0f, Motion.tw(130)) }
+ }
+ onClosed()
+ }
+ }
+ Box(
+ Modifier.fillMaxSize().graphicsLayer { alpha = fade.value }.background(Color(0x8C000000))
+ .clickable(remember { MutableInteractionSource() }, null, enabled = open) { onClose() },
+ )
+ Column(
+ Modifier.offset { IntOffset(panel.left.roundToInt(), panel.top.roundToInt()) }
+ .size(with(density) { panel.width.toDp() }, with(density) { panel.height.toDp() })
+ .graphicsLayer {
+ // Grows from where the pet is right now, so the two travel together while the pet hops to its corner.
+ transformOrigin = androidx.compose.ui.graphics.TransformOrigin(
+ ((motion.x + motion.size / 2 - panel.left) / panel.width.coerceAtLeast(1f)).coerceIn(0f, 1f),
+ ((motion.y + motion.size / 2 - panel.top) / panel.height.coerceAtLeast(1f)).coerceIn(0f, 1f),
+ )
+ val s = 0.12f + 0.88f * grow.value
+ scaleX = s
+ scaleY = s
+ alpha = fade.value
+ }
+ .clip(Shape16).background(colors.background).border(1.dp, pal.line, Shape16)
+ .clickable(remember { MutableInteractionSource() }, null, enabled = open) {}
+ .padding(start = 12.dp, end = 12.dp, top = 6.dp),
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp)) {
+ Text(stringResource(R.string.agent_pet_name), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
+ modifier = Modifier.padding(start = 4.dp))
+ Spacer(Modifier.weight(1f))
+ HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 34.dp, tag = "agent-pet-close", onClick = onClose)
+ }
+ AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false)
+ }
+ }
+}
+
+@Composable
+internal fun PetCloseTarget(over: Boolean) {
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier.padding(4.dp).size(if (over) 84.dp else 68.dp).clip(androidx.compose.foundation.shape.CircleShape)
+ .background(Color(0xCC0E141B))
+ .border(2.dp, if (over) Color(0xFFFF5A5F) else Color(0x66FFFFFF), androidx.compose.foundation.shape.CircleShape),
+ ) { Icon(Icons.Outlined.Close, null, tint = Color.White, modifier = Modifier.size(30.dp)) }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DeeDee.kt b/app/src/main/java/com/droiddeck/launcher/ui/DeeDee.kt
new file mode 100644
index 0000000000..c2632915fc
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/ui/DeeDee.kt
@@ -0,0 +1,381 @@
+package com.droiddeck.launcher.ui
+
+import androidx.compose.animation.core.CubicBezierEasing
+import androidx.compose.animation.core.Easing
+import androidx.compose.foundation.Canvas
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.produceState
+import androidx.compose.runtime.withFrameNanos
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.PathOperation
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.drawscope.DrawScope
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.graphics.drawscope.rotate
+import androidx.compose.ui.graphics.drawscope.scale
+import androidx.compose.ui.graphics.drawscope.translate
+import androidx.compose.ui.graphics.drawscope.withTransform
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.drawText
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.rememberTextMeasurer
+import kotlin.math.PI
+
+internal enum class PetState { IDLE, WORKING, QUESTION, DONE, ERROR, SLEEP }
+
+private val White = Color(0xFFFFFFFF)
+private val Blue = Color(0xFF1A9FFF)
+private val Ink = Color(0xFF0E141B)
+private val Amber = Color(0xFFFFB627)
+private val Red = Color(0xFFFF5A5F)
+private val Slate = Color(0xFF3A4A5A)
+private val Term = Color(0xFF26303B)
+private val TermLine = Color(0xFF8FA3B6)
+
+private val EaseInOut: Easing = CubicBezierEasing(0.42f, 0f, 0.58f, 1f)
+private val EaseOut: Easing = CubicBezierEasing(0f, 0f, 0.58f, 1f)
+private val Hop: Easing = CubicBezierEasing(0.3f, 0f, 0.4f, 1f)
+private val Pop: Easing = CubicBezierEasing(0.3f, 1.6f, 0.5f, 1f)
+private val Linear = Easing { it }
+private val Step = Easing { 0f }
+
+/** Where 0..1 of a loop [period] seconds long is at [time]; [lead] starts it that many seconds early. */
+private fun loop(time: Float, period: Float, lead: Float = 0f): Float {
+ val t = (time + lead) % period
+ return (if (t < 0) t + period else t) / period
+}
+
+/** A CSS-style keyframe track: [stops] holds (position, value) pairs, eased per segment. */
+private fun track(p: Float, easing: Easing, vararg stops: Float): Float {
+ if (p <= stops[0]) return stops[1]
+ var i = 0
+ while (i + 2 < stops.size) {
+ val a = stops[i]
+ val b = stops[i + 2]
+ if (p <= b) {
+ val t = if (b > a) (p - a) / (b - a) else 1f
+ return stops[i + 1] + (stops[i + 3] - stops[i + 1]) * easing.transform(t)
+ }
+ i += 2
+ }
+ return stops[stops.size - 1]
+}
+
+private fun mix(a: Color, b: Color, t: Float) = Color(
+ a.red + (b.red - a.red) * t, a.green + (b.green - a.green) * t, a.blue + (b.blue - a.blue) * t, a.alpha + (b.alpha - a.alpha) * t,
+)
+
+/** The DroidDeck mark the head is drawn from, in its own 128 by 223.72 space. */
+private val headMark: Path by lazy {
+ val d = Path().apply {
+ moveTo(-31.98f, 0f)
+ lineTo(63.97f, 0f)
+ cubicTo(125.81f, 0f, 175.93f, 50.08f, 175.93f, 111.86f)
+ cubicTo(175.93f, 173.64f, 125.81f, 223.72f, 63.97f, 223.72f)
+ lineTo(-31.98f, 223.72f)
+ close()
+ }
+ val cut = Path().apply {
+ addOval(Rect(Offset(63.98f, 111.86f), 71.81f))
+ addRect(Rect(56.055f, 0f, 56.055f + 15.83f, 45f))
+ addRect(Rect(56.055f, 178.72f, 56.055f + 15.83f, 223.72f))
+ }
+ Path.combine(PathOperation.Difference, d, cut)
+}
+
+private fun star(x: Float, y: Float, a: Float) = Path().apply {
+ moveTo(x, y - a)
+ quadraticBezierTo(x, y, x + a, y)
+ quadraticBezierTo(x, y, x, y + a)
+ quadraticBezierTo(x, y, x - a, y)
+ quadraticBezierTo(x, y, x, y - a)
+ close()
+}
+
+private class Spark(val x: Float, val y: Float, val size: Float, val color: Color, val lead: Float)
+
+private val sparks = listOf(
+ Spark(90f, 120f, 14f, White, 0f), Spark(318f, 110f, 12f, Blue, 0.4f), Spark(104f, 210f, 9f, Blue, 0.8f),
+ Spark(312f, 200f, 10f, White, 0.4f), Spark(250f, 40f, 8f, White, 0f),
+).map { it to star(it.x, it.y, it.size) }
+
+/** The rig of the DeeDee mock (a 400 by 360 view box) looping through [state]; [crop] is the part of the view box shown. */
+@Composable
+internal fun DeeDee(state: PetState, modifier: Modifier, crop: Rect = Rect(35f, 15f, 365f, 345f)) {
+ val time by produceState(0f) {
+ val start = withFrameNanos { it }
+ while (true) withFrameNanos { value = (it - start) / 1_000_000_000f }
+ }
+ val text = rememberTextMeasurer()
+ Canvas(modifier) {
+ val k = minOf(size.width / crop.width, size.height / crop.height)
+ withTransform({
+ translate((size.width - crop.width * k) / 2, (size.height - crop.height * k) / 2)
+ scale(k, k, Offset.Zero)
+ translate(-crop.left, -crop.top)
+ }) { rig(state, time, text) }
+ }
+}
+
+private fun DrawScope.rig(state: PetState, t: Float, text: androidx.compose.ui.text.TextMeasurer) {
+ // Shadow under the feet.
+ var shadowX = 1f
+ var shadowAlpha = 0.4f
+ when (state) {
+ PetState.IDLE -> shadowX = track(loop(t, 3f), EaseInOut, 0f, 1f, 0.5f, 0.9f, 1f, 1f)
+ PetState.DONE -> {
+ val p = loop(t, 1.2f)
+ shadowX = track(p, Hop, 0f, 1f, 0.15f, 1f, 0.45f, 0.7f, 0.75f, 1f, 1f, 1f)
+ shadowAlpha = track(p, Hop, 0f, 0.4f, 0.15f, 0.4f, 0.45f, 0.2f, 0.75f, 0.4f, 1f, 0.4f)
+ }
+ else -> Unit
+ }
+ scale(shadowX, 1f, Offset(200f, 336f)) {
+ drawOval(Color.Black.copy(alpha = shadowAlpha), Offset(130f, 327f), Size(140f, 18f))
+ }
+
+ // The whole body moves together.
+ var dx = 0f
+ var dy = 0f
+ var sx = 1f
+ var sy = 1f
+ when (state) {
+ PetState.IDLE -> dy = track(loop(t, 3f), EaseInOut, 0f, 0f, 0.5f, -6f, 1f, 0f)
+ PetState.WORKING -> dy = track(loop(t, 1.6f), EaseInOut, 0f, 0f, 0.5f, -2f, 1f, 0f)
+ PetState.QUESTION -> dy = track(loop(t, 2.4f), EaseInOut, 0f, 0f, 0.5f, -4f, 1f, 0f)
+ PetState.DONE -> {
+ val p = loop(t, 1.2f)
+ dy = track(p, Hop, 0f, 0f, 0.15f, 0f, 0.45f, -30f, 0.75f, 0f, 1f, 0f)
+ sx = track(p, Hop, 0f, 1.03f, 0.15f, 1f, 0.75f, 1f, 0.85f, 1.04f, 1f, 1.03f)
+ sy = track(p, Hop, 0f, 0.96f, 0.15f, 1f, 0.75f, 1f, 0.85f, 0.95f, 1f, 0.96f)
+ }
+ PetState.ERROR -> dx = track(loop(t, 2f), EaseInOut, 0f, 0f, 0.04f, -7f, 0.08f, 7f, 0.12f, -5f, 0.16f, 5f, 0.2f, -2f, 0.24f, 2f, 0.3f, 0f, 1f, 0f)
+ PetState.SLEEP -> {
+ val p = loop(t, 4f)
+ sx = track(p, EaseInOut, 0f, 1f, 0.5f, 1.02f, 1f, 1f)
+ sy = track(p, EaseInOut, 0f, 1f, 0.5f, 0.97f, 1f, 1f)
+ }
+ }
+ val alarm = if (state == PetState.ERROR) track(loop(t, 2f), EaseInOut, 0f, 0f, 0.04f, 1f, 0.24f, 1f, 0.3f, 0f, 1f, 0f) else 0f
+ withTransform({
+ translate(dx, dy)
+ scale(sx, sy, Offset(200f, 317f))
+ }) {
+ legs()
+ body(state, t, alarm)
+ if (state == PetState.WORKING) terminal(t)
+ arms(state, t)
+ head(state, t, alarm)
+ }
+ extras(state, t, text)
+}
+
+private fun DrawScope.legs() {
+ for ((x, y, w, h, r) in listOf(
+ floatArrayOf(166f, 283f, 18f, 30f, 8f), floatArrayOf(216f, 283f, 18f, 30f, 8f),
+ floatArrayOf(158f, 305f, 30f, 12f, 6f), floatArrayOf(212f, 305f, 30f, 12f, 6f),
+ )) drawRoundRect(White, Offset(x, y), Size(w, h), CornerRadius(r))
+}
+
+private operator fun FloatArray.component5() = this[4]
+
+private fun DrawScope.body(state: PetState, t: Float, alarm: Float) {
+ drawRect(White, Offset(194f, 200f), Size(12f, 20f))
+ drawRoundRect(White, Offset(148f, 215f), Size(104f, 72f), CornerRadius(22f))
+ val glow = when (state) {
+ PetState.WORKING -> track(loop(t, 0.8f), EaseInOut, 0f, 1f, 0.5f, 0.5f, 1f, 1f)
+ PetState.SLEEP -> track(loop(t, 4f), EaseInOut, 0f, 0.35f, 0.5f, 0.8f, 1f, 0.35f)
+ else -> 1f
+ }
+ drawCircle(mix(Blue, Red, alarm).copy(alpha = glow), 11f, Offset(200f, 251f))
+}
+
+private fun DrawScope.terminal(t: Float) {
+ drawRoundRect(Term, Offset(150f, 256f), Size(100f, 40f), CornerRadius(8f))
+ drawRoundRect(Blue, Offset(150f, 256f), Size(100f, 40f), CornerRadius(8f), style = Stroke(3f))
+ drawRoundRect(Blue, Offset(160f, 266f), Size(44f, 5f), CornerRadius(2.5f))
+ val grow = track(loop(t, 1.6f), EaseOut, 0f, 0.1f, 0.7f, 1f, 1f, 1f)
+ scale(grow, 1f, Offset(160f, 278f)) { drawRoundRect(TermLine, Offset(160f, 276f), Size(60f, 5f), CornerRadius(2.5f)) }
+ val cursor = track(loop(t, 0.7f), Step, 0f, 1f, 0.5f, 0.2f, 1f, 0.2f)
+ drawRoundRect(White.copy(alpha = cursor), Offset(224f, 276f), Size(10f, 5f), CornerRadius(2f))
+}
+
+/** One arm: from the shoulder through a curve to the hand, turned about the shoulder. */
+private fun DrawScope.arm(shoulder: Offset, control: Offset, hand: Offset, degrees: Float) {
+ rotate(degrees, shoulder) {
+ val path = Path().apply {
+ moveTo(shoulder.x, shoulder.y)
+ quadraticBezierTo(control.x, control.y, hand.x, hand.y)
+ }
+ drawPath(path, White, style = Stroke(10f, cap = StrokeCap.Round))
+ drawCircle(White, 9f, hand)
+ }
+}
+
+private fun DrawScope.arms(state: PetState, t: Float) {
+ val l = Offset(151f, 236f)
+ val r = Offset(249f, 236f)
+ when (state) {
+ PetState.IDLE -> {
+ val sway = track(loop(t, 3f), EaseInOut, 0f, 0f, 0.5f, 4f, 1f, 0f)
+ arm(l, Offset(127f, 246f), Offset(123f, 276f), sway)
+ arm(r, Offset(273f, 246f), Offset(277f, 276f), sway)
+ }
+ PetState.WORKING -> {
+ val p = loop(t, 0.32f)
+ arm(l, Offset(133f, 258f), Offset(157f, 270f), track(p, EaseInOut, 0f, 0f, 0.5f, -6f, 1f, 0f))
+ arm(r, Offset(267f, 258f), Offset(243f, 270f), track(p, EaseInOut, 0f, -5f, 0.5f, 1f, 1f, -5f))
+ }
+ PetState.QUESTION -> {
+ arm(l, Offset(127f, 246f), Offset(123f, 276f), 0f)
+ arm(r, Offset(279f, 230f), Offset(287f, 198f), track(loop(t, 0.9f), EaseInOut, 0f, -8f, 0.5f, 14f, 1f, -8f))
+ }
+ PetState.DONE -> {
+ val p = loop(t, 1.2f)
+ arm(l, Offset(121f, 230f), Offset(115f, 196f), track(p, EaseInOut, 0f, 0f, 0.45f, 12f, 1f, 0f))
+ arm(r, Offset(279f, 230f), Offset(285f, 196f), track(p, EaseInOut, 0f, 0f, 0.45f, -12f, 1f, 0f))
+ }
+ PetState.ERROR, PetState.SLEEP -> {
+ arm(Offset(151f, 238f), Offset(137f, 254f), Offset(135f, 284f), 0f)
+ arm(Offset(249f, 238f), Offset(263f, 254f), Offset(265f, 284f), 0f)
+ }
+ }
+}
+
+private fun DrawScope.head(state: PetState, t: Float, alarm: Float) {
+ val tilt = when (state) {
+ PetState.QUESTION -> track(loop(t, 2.4f), EaseInOut, 0f, -9f, 0.5f, -5f, 1f, -9f)
+ PetState.SLEEP -> 6f
+ else -> 0f
+ }
+ withTransform({
+ rotate(tilt, Offset(200f, 215f))
+ if (state == PetState.SLEEP) translate(0f, 6f)
+ }) {
+ antenna(state, t)
+ withTransform({
+ translate(200f, 150f)
+ scale(0.62f, 0.62f, Offset.Zero)
+ translate(-64f, -111.86f)
+ }) {
+ drawPath(headMark, White)
+ drawCircle(mix(Blue, Red, alarm).copy(alpha = if (state == PetState.SLEEP) 0.6f else 1f), 55.98f, Offset(63.98f, 111.86f))
+ }
+ eye(state, t)
+ if (state == PetState.WORKING) {
+ val sweep = 46f / (2f * PI.toFloat() * 39.6f) * 360f
+ rotate(360f * loop(t, 1.1f), Offset(200f, 150f)) {
+ drawArc(Blue, 0f, sweep, false, Offset(160.4f, 110.4f), Size(79.2f, 79.2f), style = Stroke(5f, cap = StrokeCap.Round))
+ }
+ }
+ }
+}
+
+private fun DrawScope.antenna(state: PetState, t: Float) {
+ val lean = when (state) {
+ PetState.ERROR -> 22f
+ PetState.SLEEP -> -28f
+ else -> 0f
+ }
+ rotate(lean, Offset(200f, 100f)) {
+ drawLine(White, Offset(200f, 100f), Offset(200f, 52f), 7f, StrokeCap.Round)
+ var radius = 10f
+ val (color, alpha) = when (state) {
+ PetState.IDLE -> Blue to track(loop(t, 3f), EaseInOut, 0f, 1f, 0.5f, 0.45f, 1f, 1f)
+ PetState.WORKING -> Blue to track(loop(t, 0.5f), Step, 0f, 1f, 0.5f, 0.2f, 1f, 0.2f)
+ PetState.QUESTION -> {
+ val p = loop(t, 1f)
+ radius = track(p, EaseInOut, 0f, 10f, 0.5f, 13f, 1f, 10f)
+ Amber to track(p, EaseInOut, 0f, 1f, 0.5f, 0.5f, 1f, 1f)
+ }
+ PetState.DONE -> Blue to 1f
+ PetState.ERROR -> Red to track(loop(t, 1f), Step, 0f, 1f, 0.5f, 0.25f, 1f, 0.25f)
+ PetState.SLEEP -> Slate to 1f
+ }
+ drawCircle(color.copy(alpha = alpha), radius, Offset(200f, 45f))
+ }
+}
+
+private fun DrawScope.eye(state: PetState, t: Float) {
+ when (state) {
+ PetState.DONE -> drawPath(Path().apply { moveTo(186f, 156f); quadraticBezierTo(203f, 136f, 220f, 156f) }, Ink, style = Stroke(7f, cap = StrokeCap.Round))
+ PetState.SLEEP -> drawPath(Path().apply { moveTo(186f, 152f); quadraticBezierTo(203f, 162f, 220f, 152f) }, Ink, style = Stroke(6f, cap = StrokeCap.Round))
+ PetState.ERROR -> {
+ val stroke = 6f
+ drawLine(Ink, Offset(193f, 139f), Offset(215f, 161f), stroke, StrokeCap.Round)
+ drawLine(Ink, Offset(215f, 139f), Offset(193f, 161f), stroke, StrokeCap.Round)
+ }
+ else -> {
+ val blink = if (state == PetState.IDLE) track(loop(t, 4.5f), EaseInOut, 0f, 1f, 0.44f, 1f, 0.47f, 0.1f, 0.5f, 1f, 1f, 1f) else 1f
+ val (px, py) = when (state) {
+ PetState.IDLE -> track(loop(t, 9f), EaseInOut, 0f, 0f, 0.3f, 0f, 0.36f, -7f, 0.52f, -7f, 0.58f, 5f, 0.8f, 5f, 0.86f, 0f, 1f, 0f) to 0f
+ PetState.WORKING -> track(loop(t, 1.6f), EaseInOut, 0f, -7f, 0.5f, 6f, 1f, -7f) to 0f
+ else -> 5f to -5f
+ }
+ scale(1f, blink, Offset(204f, 149f)) {
+ translate(px, py) {
+ drawCircle(Ink, 16f, Offset(204f, 149f))
+ drawCircle(White, 5f, Offset(210f, 143f))
+ drawCircle(White.copy(alpha = 0.7f), 2.2f, Offset(199f, 155f))
+ }
+ }
+ }
+ }
+}
+
+private fun DrawScope.speechTail(color: Color) {
+ drawPath(Path().apply { moveTo(264f, 82f); lineTo(254f, 100f); lineTo(278f, 86f); close() }, color)
+}
+
+private fun DrawScope.extras(state: PetState, t: Float, text: androidx.compose.ui.text.TextMeasurer) {
+ when (state) {
+ PetState.QUESTION -> {
+ val p = loop(t, 2.4f)
+ val s = track(p, Pop, 0f, 0.4f, 0.12f, 1f, 0.88f, 1f, 1f, 0.9f)
+ val a = track(p, Pop, 0f, 0f, 0.12f, 1f, 0.88f, 1f, 1f, 0f).coerceIn(0f, 1f)
+ scale(s, s, Offset(262f, 96f)) {
+ drawRoundRect(Amber.copy(alpha = a), Offset(254f, 30f), Size(62f, 58f), CornerRadius(18f))
+ speechTail(Amber.copy(alpha = a))
+ val mark = text.measure("?", TextStyle(color = Ink.copy(alpha = a), fontSize = 42f.toSp(), fontWeight = FontWeight.Bold))
+ drawText(mark, topLeft = Offset(285f - mark.size.width / 2f, 74f - mark.firstBaseline))
+ }
+ }
+ PetState.ERROR -> {
+ val nudge = track(loop(t, 2f), EaseInOut, 0f, 0f, 0.06f, -10f, 0.14f, 8f, 0.22f, -4f, 0.3f, 0f, 1f, 0f)
+ rotate(nudge, Offset(262f, 96f)) {
+ drawRoundRect(Red, Offset(254f, 34f), Size(54f, 54f), CornerRadius(16f))
+ speechTail(Red)
+ drawRoundRect(White, Offset(277f, 44f), Size(8f, 24f), CornerRadius(4f))
+ drawCircle(White, 5f, Offset(281f, 77f))
+ }
+ }
+ PetState.DONE -> for ((spark, path) in sparks) {
+ val p = loop(t, 1.2f, spark.lead)
+ val s = track(p, EaseInOut, 0f, 0f, 0.4f, 1f, 0.7f, 0.6f, 1f, 0f)
+ val turn = track(p, EaseInOut, 0f, 0f, 0.4f, 45f, 0.7f, 90f, 1f, 0f)
+ val a = track(p, EaseInOut, 0f, 0f, 0.4f, 1f, 0.7f, 0.8f, 1f, 0f)
+ if (s <= 0.01f) continue
+ withTransform({
+ rotate(turn, Offset(spark.x, spark.y))
+ scale(s, s, Offset(spark.x, spark.y))
+ }) { drawPath(path, spark.color.copy(alpha = a)) }
+ }
+ PetState.SLEEP -> for ((i, z) in listOf(Triple(250f, 96f, 22f), Triple(268f, 74f, 30f), Triple(286f, 52f, 38f)).withIndex()) {
+ val p = loop(t, 4f, -1.3f * i)
+ val a = track(p, EaseOut, 0f, 0f, 0.2f, 1f, 1f, 0f)
+ val zx = track(p, EaseOut, 0f, -10f, 1f, 14f)
+ val zy = track(p, EaseOut, 0f, 16f, 1f, -22f)
+ val glyph = text.measure("z", TextStyle(color = White.copy(alpha = a), fontSize = z.third.toSp(), fontWeight = FontWeight.Bold))
+ // The view box places a glyph by its baseline.
+ drawText(glyph, topLeft = Offset(z.first + zx, z.second + zy - glyph.firstBaseline))
+ }
+ else -> Unit
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/EdgeFling.kt b/app/src/main/java/com/droiddeck/launcher/ui/EdgeFling.kt
new file mode 100644
index 0000000000..700d031776
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/ui/EdgeFling.kt
@@ -0,0 +1,92 @@
+package com.droiddeck.launcher.ui
+
+import android.view.Choreographer
+import kotlin.math.abs
+import kotlin.math.sqrt
+
+/**
+ * Where something dragged and let go against the side edges, like a chat head, comes to rest:
+ * a quick sideways flick sends it to the side it was thrown toward from wherever it is; a slower
+ * release goes to the side its coasting would carry it to; and its height carries on with the
+ * throw. Velocities are pixels per second.
+ */
+internal object EdgeFling {
+ /** How far a throw coasts, in seconds of its release velocity. */
+ const val COAST_S = 0.18f
+ /** A sideways speed past this many dp per second picks its side outright. */
+ private const val FLICK_DP_S = 600f
+
+ fun toRight(centerX: Float, span: Float, vx: Float, density: Float): Boolean {
+ if (abs(vx) > FLICK_DP_S * density) return vx > 0
+ return centerX + vx * COAST_S > span / 2
+ }
+
+ fun restY(y: Float, vy: Float, min: Float, max: Float) = (y + vy * COAST_S).coerceIn(min, max.coerceAtLeast(min))
+}
+
+/**
+ * A spring in two dimensions that starts with the velocity it was let go with, stepped on each
+ * display frame, so a throw flows into its settle instead of starting over from rest.
+ */
+internal class FlingSpring(
+ private val stiffness: Float = 340f,
+ dampingRatio: Float = 0.74f,
+ private val onFrame: (Float, Float) -> Unit,
+) : Choreographer.FrameCallback {
+ private val damping = 2f * dampingRatio * sqrt(stiffness)
+ private var x = 0f
+ private var y = 0f
+ private var vx = 0f
+ private var vy = 0f
+ private var toX = 0f
+ private var toY = 0f
+ private var last = 0L
+ private var onEnd: (() -> Unit)? = null
+ var running = false
+ private set
+
+ fun start(fromX: Float, fromY: Float, velocityX: Float, velocityY: Float, targetX: Float, targetY: Float, end: (() -> Unit)? = null) {
+ cancel()
+ x = fromX; y = fromY; vx = velocityX; vy = velocityY; toX = targetX; toY = targetY
+ onEnd = end
+ if (Motion.scale == 0f) {
+ onFrame(toX, toY)
+ end?.invoke()
+ return
+ }
+ running = true
+ last = 0L
+ Choreographer.getInstance().postFrameCallback(this)
+ }
+
+ fun cancel() {
+ if (!running) return
+ running = false
+ Choreographer.getInstance().removeFrameCallback(this)
+ }
+
+ override fun doFrame(frameTimeNanos: Long) {
+ if (!running) return
+ val dt = if (last == 0L) 1f / 120f else ((frameTimeNanos - last) / 1e9f).coerceIn(0f, 1f / 20f)
+ last = frameTimeNanos
+ // Small fixed steps keep the spring stable however long a frame took.
+ var left = dt / Motion.scale.coerceAtLeast(0.1f)
+ while (left > 0f) {
+ val h = minOf(left, 1f / 480f)
+ vx += (-stiffness * (x - toX) - damping * vx) * h
+ vy += (-stiffness * (y - toY) - damping * vy) * h
+ x += vx * h
+ y += vy * h
+ left -= h
+ }
+ val settled = abs(x - toX) < 0.5f && abs(y - toY) < 0.5f && abs(vx) < 20f && abs(vy) < 20f
+ if (settled) {
+ running = false
+ onFrame(toX, toY)
+ onEnd?.invoke()
+ return
+ }
+ onFrame(x, y)
+ Choreographer.getInstance().postFrameCallback(this)
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt
index 3354839a7d..c3a5bb3784 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt
@@ -459,6 +459,13 @@ internal fun SetupPanel(
ToggleRow(host, "agent-tab", stringResource(R.string.setup_agent_tab), null, com.droiddeck.launcher.agent.AgentTab.shown) {
com.droiddeck.launcher.agent.AgentTab.set(railContext, it)
}
+ ToggleRow(host, "agent-pet", stringResource(R.string.setup_agent_pet), stringResource(R.string.setup_agent_pet_hint), AgentPet.enabled) {
+ AgentPet.set(railContext, it)
+ }
+ if (AgentPet.enabled && !AgentPet.allowed) ActionRow(
+ stringResource(R.string.setup_agent_pet_float), stringResource(R.string.setup_agent_pet_float_hint),
+ stringResource(R.string.setup_agent_pet_allow), onClick = { AgentPet.requestFloating(railContext) },
+ )
}
LanguageRow(host, s.language, a.onLanguage)
ToggleRow(host, "show-stores", stringResource(R.string.setup_stores), null, s.gameStoresEnabled, onChange = a.onGameStoresEnabled)
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index cc7c632ddb..d98d3e6462 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -2689,6 +2689,13 @@
Sidebar labels
Show names under the sidebar icons. Turn off for a slimmer sidebar.
Agent tab
+ Agent pet
+ DeeDee floats over the launcher and games and shows what the agent is doing.
+ Over other apps
+ Let DeeDee float over every app and open its chat there
+ Allow
+ DeeDee
+ Chat with DeeDee
Display
Larger cards
Smaller cards
diff --git a/app/src/test/java/com/droiddeck/launcher/ui/EdgeFlingTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/EdgeFlingTest.kt
new file mode 100644
index 0000000000..5a0e298541
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/ui/EdgeFlingTest.kt
@@ -0,0 +1,27 @@
+package com.droiddeck.launcher.ui
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class EdgeFlingTest {
+ private val density = 2f
+
+ @Test fun aQuickFlickGoesTheWayItWasThrownFromAnywhere() {
+ assertFalse(EdgeFling.toRight(centerX = 1800f, span = 1920f, vx = -1500f, density = density))
+ assertTrue(EdgeFling.toRight(centerX = 100f, span = 1920f, vx = 1500f, density = density))
+ }
+
+ @Test fun aSlowReleaseGoesWhereItWouldCoast() {
+ assertTrue(EdgeFling.toRight(centerX = 1000f, span = 1920f, vx = 0f, density = density))
+ assertFalse(EdgeFling.toRight(centerX = 900f, span = 1920f, vx = 0f, density = density))
+ assertFalse(EdgeFling.toRight(centerX = 1100f, span = 1920f, vx = -1100f, density = density))
+ }
+
+ @Test fun theHeightCarriesOnWithTheThrowAndStaysOnScreen() {
+ assertEquals(436f, EdgeFling.restY(400f, 200f, 0f, 1000f), 0.01f)
+ assertEquals(1000f, EdgeFling.restY(900f, 5000f, 0f, 1000f), 0.01f)
+ assertEquals(24f, EdgeFling.restY(100f, -5000f, 24f, 1000f), 0.01f)
+ }
+}