Skip to content

armgit / andee

Public Imported from GitHub
0

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(desktop): the ball floats above every app, as on the phone

booboosuibefd84848345
diff --git a/desktop/build.gradle b/desktop/build.gradle
index 6a05fbd..ff035c9 100644
--- a/desktop/build.gradle
+++ b/desktop/build.gradle
@@ -43,6 +43,11 @@ dependencies {
implementation 'org.json:json:20240303'
// Calls into native/AndeeMac.swift.
implementation 'net.java.dev.jna:jna:5.14.0'
+ // LWJGL: OpenGL and CGL for the ball's offscreen renderer (no GLFW — see BallRenderer).
+ implementation 'org.lwjgl:lwjgl:3.3.4'
+ implementation 'org.lwjgl:lwjgl-opengl:3.3.4'
+ implementation "org.lwjgl:lwjgl:3.3.4:natives-macos-arm64"
+ implementation "org.lwjgl:lwjgl-opengl:3.3.4:natives-macos-arm64"
testImplementation libs.junit
}
@@ -53,6 +58,10 @@ compose.desktop {
nativeDistributions {
targetFormats(TargetFormat.Dmg)
packageName = 'Andee'
+ // The packaged runtime is trimmed to what jlink sees used; LWJGL (the
+ // ball's OpenGL) reaches sun.misc.Unsafe reflectively, so name it, or the
+ // ball silently fails only in the .app and never under `gradle run`.
+ modules('jdk.unsupported')
// macOS rejects a 0.x bundle version for a .dmg; 1.0.0 is the bundle's
// version, not the product's.
packageVersion = '1.0.0'
@@ -94,3 +103,11 @@ tasks.named('test') {
dependsOn('buildNative')
systemProperty 'andee.trashTool', layout.buildDirectory.file('native/andee-trash').get().asFile.path
}
+
+// One frame of the ball to a PNG, to check the desktop renderer without the window:
+// ./gradlew :desktop:ballshot --args='HAPPY 336 /tmp/ball.png andee'
+tasks.register('ballshot', JavaExec) {
+ classpath = sourceSets.main.runtimeClasspath
+ mainClass = 'net.kuafuai.andee.desktop.BallShotKt'
+}
+
diff --git a/desktop/native/AndeeMac.swift b/desktop/native/AndeeMac.swift
index cbfd55d..7ef77e9 100644
--- a/desktop/native/AndeeMac.swift
+++ b/desktop/native/AndeeMac.swift
@@ -48,9 +48,67 @@ public func andee_main_display() -> UnsafeMutablePointer<CChar> {
return json(["x": b.origin.x, "y": b.origin.y, "w": b.width, "h": b.height, "scale": scale])
}
+/// The app the user is looking at, never Andee itself.
+///
+/// Asking our own process for its accessibility tree is not a question to another
+/// app: AppKit answers it inside this process, on the calling thread, by calling
+/// into AWT's Java accessibility — off the main thread, which kills the JVM
+/// (SIGBUS in CAccessibility, twice). And it is the wrong answer anyway: when
+/// Andee is frontmost it is because the user just touched the ball, and what they
+/// mean by "the screen" is the app behind it. So: the frontmost app if it is not
+/// us, else the owner of the frontmost ordinary window that is not ours.
+private func targetApp() -> NSRunningApplication? {
+ let me = getpid()
+ if let f = NSWorkspace.shared.frontmostApplication, f.processIdentifier != me { return f }
+ let opts: CGWindowListOption = [.optionOnScreenOnly, .excludeDesktopElements]
+ if let list = CGWindowListCopyWindowInfo(opts, kCGNullWindowID) as? [[String: Any]] {
+ for w in list {
+ guard (w[kCGWindowLayer as String] as? Int) == 0,
+ let pid = w[kCGWindowOwnerPID as String] as? pid_t, pid != me,
+ let app = NSRunningApplication(processIdentifier: pid),
+ app.activationPolicy == .regular else { continue }
+ return app
+ }
+ }
+ return nil
+}
+
+/// The focused element of the target app, asked of that app directly. The
+/// system-wide "focused element" is Andee's own whenever Andee is frontmost.
+private func targetFocused() -> AXUIElement? {
+ guard let app = targetApp() else { return nil }
+ let ax = AXUIElementCreateApplication(app.processIdentifier)
+ guard let f = attr(ax, kAXFocusedUIElementAttribute) else { return nil }
+ return (f as! AXUIElement)
+}
+
+/// The process whose window is frontmost at a point, skipping ours (at any alpha:
+/// ours are faded, not gone, while a click is under way). Nil when nothing but
+/// Andee is there.
+private func otherAppAt(_ x: Double, _ y: Double) -> pid_t? {
+ let me = getpid()
+ guard let list = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID)
+ as? [[String: Any]] else { return nil }
+ for w in list {
+ guard let pid = w[kCGWindowOwnerPID as String] as? pid_t, pid != me,
+ (w[kCGWindowAlpha as String] as? Double ?? 1) > 0,
+ let b = w[kCGWindowBounds as String] as? [String: Any],
+ let r = CGRect(dictionaryRepresentation: b as CFDictionary),
+ r.contains(CGPoint(x: x, y: y)) else { continue }
+ return pid
+ }
+ return nil
+}
+
+/// Whether an element belongs to this process; such an element must not be queried (see targetApp).
+private func isOurs(_ e: AXUIElement) -> Bool {
+ var pid: pid_t = 0
+ return AXUIElementGetPid(e, &pid) == .success && pid == getpid()
+}
+
@_cdecl("andee_frontmost")
public func andee_frontmost() -> UnsafeMutablePointer<CChar> {
- guard let app = NSWorkspace.shared.frontmostApplication else { return json([:]) }
+ guard let app = targetApp() else { return json([:]) }
return json(["name": app.localizedName ?? "", "bundle": app.bundleIdentifier ?? "", "pid": Int(app.processIdentifier)])
}
@@ -123,7 +181,7 @@ private func settableValue(_ e: AXUIElement) -> Bool? {
/** The frontmost app's focused window (or its first window) as a JSON tree. */
@_cdecl("andee_ax_tree")
public func andee_ax_tree(_ maxNodes: Int32) -> UnsafeMutablePointer<CChar> {
- guard let app = NSWorkspace.shared.frontmostApplication else { return json(["error": "no frontmost app"]) }
+ guard let app = targetApp() else { return json(["error": "no app window on screen besides Andee"]) }
let ax = AXUIElementCreateApplication(app.processIdentifier)
// Chromium and Electron build their tree only when asked.
AXUIElementSetAttributeValue(ax, "AXManualAccessibility" as CFString, kCFBooleanTrue)
@@ -152,26 +210,26 @@ public func andee_ax_tree(_ maxNodes: Int32) -> UnsafeMutablePointer<CChar> {
/** Press the element at an index path from the last tree (child indices from the window root). */
@_cdecl("andee_ax_press_at")
public func andee_ax_press_at(_ x: Double, _ y: Double) -> Int32 {
- let sys = AXUIElementCreateSystemWide()
+ // Never the system-wide hit test: it reaches our own windows even while they are
+ // faded out for this very click (alpha 0 still hit-tests), and asking our own
+ // process kills the JVM. Ask the app that owns the point, by name.
+ guard let pid = otherAppAt(x, y) else { return 0 } // the caller falls back to a real click
+ let app = AXUIElementCreateApplication(pid)
var el: AXUIElement?
- guard AXUIElementCopyElementAtPosition(sys, Float(x), Float(y), &el) == .success, let e = el else { return 0 }
+ guard AXUIElementCopyElementAtPosition(app, Float(x), Float(y), &el) == .success, let e = el, !isOurs(e) else { return 0 }
return AXUIElementPerformAction(e, kAXPressAction as CFString) == .success ? 1 : 0
}
/** Set the focused element's value (a text field), as a person pasting it would. */
@_cdecl("andee_ax_set_focused_value")
public func andee_ax_set_focused_value(_ text: UnsafePointer<CChar>) -> Int32 {
- let sys = AXUIElementCreateSystemWide()
- guard let f = attr(sys, kAXFocusedUIElementAttribute) else { return 0 }
- let e = f as! AXUIElement
+ guard let e = targetFocused(), !isOurs(e) else { return 0 }
return AXUIElementSetAttributeValue(e, kAXValueAttribute as CFString, String(cString: text) as CFString) == .success ? 1 : 0
}
@_cdecl("andee_ax_focused_value")
public func andee_ax_focused_value() -> UnsafeMutablePointer<CChar> {
- let sys = AXUIElementCreateSystemWide()
- guard let f = attr(sys, kAXFocusedUIElementAttribute) else { return json(["focused": false]) }
- let e = f as! AXUIElement
+ guard let e = targetFocused(), !isOurs(e) else { return json(["focused": false]) }
return json(["focused": true, "role": str(e, kAXRoleAttribute) ?? "", "value": str(e, kAXValueAttribute) ?? ""])
}
@@ -310,3 +368,53 @@ public func andee_open(_ target: UnsafePointer<CChar>) -> Int32 {
}
return NSWorkspace.shared.open(URL(fileURLWithPath: t)) ? 1 : 0
}
+
+// MARK: - the floating ball's window
+
+/// Lifts our own window titled [title] above everything, the phone's
+/// TYPE_APPLICATION_OVERLAY: above normal and floating windows, on every Space,
+/// and over other apps' full-screen Spaces. A JVM window can only ask for
+/// "always on top", which is the floating level and stays on one Space.
+@_cdecl("andee_float_window")
+public func andee_float_window(_ title: UnsafePointer<CChar>) -> Int32 {
+ let t = String(cString: title)
+ // Async on purpose: AWT's main thread may itself be waiting on the JVM's
+ // event thread, and a sync hop from there would deadlock the app.
+ DispatchQueue.main.async {
+ guard let w = NSApp?.windows.first(where: { $0.title == t }) else { return }
+ w.level = .statusBar
+ w.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle]
+ w.hidesOnDeactivate = false
+ w.hasShadow = false
+ }
+ return NSApp == nil ? 0 : 1
+}
+
+/// Fade every window of ours in or out, for the instant of a click aimed at
+/// another app. Native because AWT refuses `setOpacity` on a decorated window
+/// (the chat), and a refusal half-way left the ball invisible for good.
+/// Waits for the main thread at most half a second, never forever: the main
+/// thread can itself be waiting on the JVM.
+@_cdecl("andee_set_own_alpha")
+public func andee_set_own_alpha(_ alpha: Double) -> Int32 {
+ let done = DispatchSemaphore(value: 0)
+ DispatchQueue.main.async {
+ NSApp?.windows.forEach { $0.alphaValue = CGFloat(alpha) }
+ done.signal()
+ }
+ return done.wait(timeout: .now() + 0.5) == .success ? 1 : 0
+}
+
+/// Whether a visible window of ours covers this point — only then does a click need us out of the way.
+@_cdecl("andee_own_window_at")
+public func andee_own_window_at(_ x: Double, _ y: Double) -> Int32 {
+ let me = getpid()
+ guard let list = CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]] else { return 1 }
+ for w in list where (w[kCGWindowOwnerPID as String] as? pid_t) == me {
+ if (w[kCGWindowAlpha as String] as? Double ?? 1) == 0 { continue }
+ if let b = w[kCGWindowBounds as String] as? [String: Any],
+ let r = CGRect(dictionaryRepresentation: b as CFDictionary),
+ r.insetBy(dx: -4, dy: -4).contains(CGPoint(x: x, y: y)) { return 1 }
+ }
+ return 0
+}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt
index e804b04..c971545 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt
@@ -113,23 +113,30 @@ object Assistant {
onFinal = { text ->
val clean = net.kuafuai.andee.brain.SpeechMood.parse(text).text.replace("[END]", "").trim()
Scrollback.add(Scrollback.Role.ASSISTANT, clean)
+ MacBall.onAnswer(text)
onFinal(clean)
- onBusy(false)
+ busy(false)
if (speakReplies) net.kuafuai.andee.desktop.voice.MacVoice.speak(text)
},
- onTurnEnd = { onBusy(false) },
+ onTurnEnd = { busy(false) },
)
brain = b
builtFor = cfg
return b
}
+ /** A turn started or ended: the window's stop button and the ball's working face. */
+ private fun busy(b: Boolean) {
+ MacBall.onBusy(b)
+ onBusy(b)
+ }
+
fun say(text: String, spoken: Boolean = false) {
speakReplies = spoken
val t = text.trim()
if (t.isEmpty()) return
Scrollback.add(Scrollback.Role.USER, t)
- onBusy(true)
+ busy(true)
ensure().submit(t)
}
@@ -138,11 +145,11 @@ object Assistant {
brain?.cancel()
shell.stopAll()
net.kuafuai.andee.desktop.voice.MacVoice.stopSpeaking()
- onBusy(false)
+ busy(false)
}
fun start() {
- DesktopScheduler.onDue = { todo -> onBusy(true); ensure().wake(dueText(todo), untrusted = todo.untrusted) }
+ DesktopScheduler.onDue = { todo -> busy(true); ensure().wake(dueText(todo), untrusted = todo.untrusted) }
DesktopScheduler.catchUp()
}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/BallRenderer.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/BallRenderer.kt
new file mode 100644
index 0000000..cfe7f4e
--- /dev/null
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/BallRenderer.kt
@@ -0,0 +1,168 @@
+package net.kuafuai.andee.desktop
+
+import net.kuafuai.andee.ui.ball.Action
+import net.kuafuai.andee.ui.ball.EmotionBallRenderer
+import net.kuafuai.andee.ui.ball.Mood
+import net.kuafuai.andee.ui.ball.gl.GLES20
+import net.kuafuai.andee.util.Log
+import org.lwjgl.BufferUtils
+import org.lwjgl.PointerBuffer
+import org.lwjgl.opengl.ARBFramebufferObject as FBO
+import org.lwjgl.opengl.CGL
+import org.lwjgl.opengl.GL
+import org.lwjgl.opengl.GL11
+import java.util.concurrent.ConcurrentLinkedQueue
+import kotlin.concurrent.thread
+
+/**
+ * The phone's ball renderer, unchanged, on an offscreen OpenGL context of its own.
+ *
+ * A bare CGL context rather than a GLFW window, and that is not taste: GLFW on
+ * macOS insists on the process's first thread, which Compose/AWT already owns —
+ * the first version hung there forever, before drawing a frame. CGL needs no
+ * window and no particular thread. It is a *legacy* profile (GL 2.1, GLSL 1.20)
+ * because the shaders are GLSL ES 1.00, which [DesktopGl.adaptShader] can turn
+ * into 1.20 by dropping `precision`; a core profile would mean rewriting every
+ * `attribute`/`varying`.
+ *
+ * The renderer draws into an FBO at ~60 fps and each frame is read back into
+ * [frame] as premultiplied ARGB, bottom row flipped to the top — what the window
+ * paints. GL calls stay on this thread; the knobs are queued to it, so the
+ * renderer's own `@Volatile` contract is kept exactly as on the phone.
+ */
+class BallRenderer(val width: Int, val height: Int) {
+
+ private val renderer = EmotionBallRenderer()
+ private val commands = ConcurrentLinkedQueue<() -> Unit>()
+ @Volatile private var stopRequested = false
+
+ /** The latest finished frame: premultiplied BGRA bytes, top row first. Null until the first one. */
+ @Volatile var frame: ByteArray? = null
+ private set
+
+ /** Why the ball cannot be drawn on this Mac, if it cannot; the window falls back to no ball. */
+ @Volatile var failure: String? = null
+ private set
+
+ /** Called on the render thread after each new [frame]. */
+ @Volatile var onFrame: () -> Unit = {}
+
+ private val thread = thread(name = "BallGL", isDaemon = true) {
+ runCatching { run() }.onFailure {
+ failure = it.message ?: it.toString()
+ Log.e(TAG, "the ball cannot be drawn", it)
+ }
+ }
+
+ private fun run() {
+ val ctx = createContext()
+ try {
+ GL.createCapabilities()
+ GLES20.backend = DesktopGl
+ val fbo = FBO.glGenFramebuffers()
+ FBO.glBindFramebuffer(FBO.GL_FRAMEBUFFER, fbo)
+ val color = FBO.glGenRenderbuffers()
+ FBO.glBindRenderbuffer(FBO.GL_RENDERBUFFER, color)
+ FBO.glRenderbufferStorage(FBO.GL_RENDERBUFFER, GL11.GL_RGBA8, width, height)
+ FBO.glFramebufferRenderbuffer(FBO.GL_FRAMEBUFFER, FBO.GL_COLOR_ATTACHMENT0, FBO.GL_RENDERBUFFER, color)
+ val depth = FBO.glGenRenderbuffers()
+ FBO.glBindRenderbuffer(FBO.GL_RENDERBUFFER, depth)
+ FBO.glRenderbufferStorage(FBO.GL_RENDERBUFFER, org.lwjgl.opengl.GL14.GL_DEPTH_COMPONENT16, width, height)
+ FBO.glFramebufferRenderbuffer(FBO.GL_FRAMEBUFFER, FBO.GL_DEPTH_ATTACHMENT, FBO.GL_RENDERBUFFER, depth)
+ val status = FBO.glCheckFramebufferStatus(FBO.GL_FRAMEBUFFER)
+ check(status == FBO.GL_FRAMEBUFFER_COMPLETE) { "framebuffer incomplete: 0x${status.toString(16)}" }
+
+ // ES 2.0 always sizes points from gl_PointSize and always fills gl_PointCoord;
+ // a legacy desktop context does neither until asked, and the blush and the
+ // dust would draw as one-pixel squares.
+ GL11.glEnable(org.lwjgl.opengl.GL20.GL_VERTEX_PROGRAM_POINT_SIZE)
+ GL11.glEnable(org.lwjgl.opengl.GL20.GL_POINT_SPRITE)
+ renderer.onSurfaceCreated()
+ renderer.onSurfaceChanged(width, height)
+ val buf = BufferUtils.createByteBuffer(width * height * 4)
+ while (!stopRequested) {
+ val t0 = System.nanoTime()
+ while (true) commands.poll()?.invoke() ?: break
+ renderer.onDrawFrame()
+ buf.clear()
+ GL11.glReadPixels(0, 0, width, height, org.lwjgl.opengl.GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, buf)
+ frame = flipped(buf)
+ onFrame()
+ val sleep = (FRAME_NS - (System.nanoTime() - t0)) / 1_000_000
+ if (sleep > 0) Thread.sleep(sleep)
+ }
+ FBO.glDeleteRenderbuffers(depth)
+ FBO.glDeleteRenderbuffers(color)
+ FBO.glDeleteFramebuffers(fbo)
+ } finally {
+ CGL.CGLSetCurrentContext(0L)
+ CGL.CGLDestroyContext(ctx)
+ }
+ }
+
+ private fun createContext(): Long {
+ val attrs = intArrayOf(
+ CGL.kCGLPFAOpenGLProfile, CGL.kCGLOGLPVersion_Legacy,
+ CGL.kCGLPFAColorSize, 24,
+ CGL.kCGLPFAAlphaSize, 8,
+ CGL.kCGLPFADepthSize, 16,
+ CGL.kCGLPFAAccelerated,
+ 0,
+ )
+ val pix = PointerBuffer.allocateDirect(1)
+ val n = IntArray(1)
+ var err = CGL.CGLChoosePixelFormat(attrs, pix, n)
+ check(err == 0 && pix[0] != 0L) { "CGLChoosePixelFormat failed ($err)" }
+ val ctx = PointerBuffer.allocateDirect(1)
+ err = CGL.CGLCreateContext(pix[0], 0L, ctx)
+ CGL.CGLDestroyPixelFormat(pix[0])
+ check(err == 0 && ctx[0] != 0L) { "CGLCreateContext failed ($err)" }
+ check(CGL.CGLSetCurrentContext(ctx[0]) == 0) { "CGLSetCurrentContext failed" }
+ return ctx[0]
+ }
+
+ /**
+ * GL's bottom-up rows → Skia's top-down. Already premultiplied: blending
+ * onto a cleared-transparent target is what the phone's non-opaque
+ * TextureView composites as premultiplied too, so both apps read it alike.
+ */
+ private fun flipped(buf: java.nio.ByteBuffer): ByteArray {
+ val row = width * 4
+ val out = ByteArray(row * height)
+ for (y in 0 until height) {
+ buf.position((height - 1 - y) * row)
+ buf.get(out, y * row, row)
+ }
+ buf.position(0)
+ return out
+ }
+
+ fun setState(mood: Mood, listening: Boolean, emotion: Mood?) = post {
+ renderer.mood = mood
+ renderer.listening = listening
+ renderer.emotion = emotion
+ }
+
+ fun setEmotion(m: Mood?) = post { renderer.emotion = m }
+ fun setWorking(w: Boolean) = post { renderer.working = w }
+ fun pulseTool() = post { renderer.pulseTool() }
+ fun signalOutcome(ok: Boolean) = post { renderer.signalOutcome(ok) }
+ fun trigger(action: Action) = post { renderer.request(action) }
+
+ private fun post(f: () -> Unit) { commands.offer(f) }
+
+ fun stop() {
+ stopRequested = true
+ thread.join(2000)
+ }
+
+ private companion object {
+ const val TAG = "Ball"
+ /**
+ * 30 fps. The ball's motion is slow springs and breathing, which read the
+ * same at 30 as at 60; the frame is then read back and handed to another
+ * window, so every frame costs twice, and halving them is most of the CPU.
+ */
+ const val FRAME_NS = 33_333_333L
+ }
+}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/BallShot.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/BallShot.kt
new file mode 100644
index 0000000..dcf1194
--- /dev/null
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/BallShot.kt
@@ -0,0 +1,52 @@
+package net.kuafuai.andee.desktop
+
+import net.kuafuai.andee.ui.ball.BallLooks
+import net.kuafuai.andee.ui.ball.Mood
+import java.awt.image.BufferedImage
+import java.io.File
+import javax.imageio.ImageIO
+import kotlin.system.exitProcess
+
+/**
+ * One frame of the ball to a PNG, for checking the desktop renderer without the window:
+ * `./gradlew :desktop:ballshot --args='HAPPY 336 /tmp/ball.png andee'`
+ */
+fun main(args: Array<String>) {
+ net.kuafuai.andee.util.Log.sink = object : net.kuafuai.andee.util.Log.Sink {
+ override fun log(level: Char, tag: String, msg: String, t: Throwable?) {
+ System.err.println("$level/$tag: $msg"); t?.printStackTrace()
+ }
+ }
+ val mood = Mood.valueOf(args.getOrElse(0) { "CALM" })
+ val size = args.getOrElse(1) { "336" }.toInt()
+ val out = File(args.getOrElse(2) { "/tmp/ball.png" })
+ args.getOrNull(3)?.let { BallLooks.requestByName(it) }
+ val r = BallRenderer(size, size)
+ if (System.getenv("BALL_BENCH") != null) {
+ // How much CPU the renderer alone costs, without any window: ten seconds of frames.
+ val os = java.lang.management.ManagementFactory.getOperatingSystemMXBean() as com.sun.management.OperatingSystemMXBean
+ Thread.sleep(2000)
+ val c0 = os.processCpuTime; val t0 = System.nanoTime()
+ Thread.sleep(10_000)
+ println("renderer alone: %.1f%% of one core".format(100.0 * (os.processCpuTime - c0) / (System.nanoTime() - t0)))
+ exitProcess(0)
+ }
+ r.setState(mood, listening = mood == Mood.LISTENING, emotion = null)
+ // Wait for the first frame, then let the face settle into the mood for a second and a half.
+ val deadline = System.currentTimeMillis() + 10_000
+ while (r.failure == null && r.frame == null && System.currentTimeMillis() < deadline) Thread.sleep(50)
+ if (r.frame != null) Thread.sleep(1500)
+ r.failure?.let { System.err.println("failed: $it"); exitProcess(1) }
+ val px = r.frame ?: run { System.err.println("no frame in 10 s"); exitProcess(1) }
+ val argb = IntArray(size * size) { i ->
+ val j = i * 4
+ ((px[j + 3].toInt() and 0xff) shl 24) or ((px[j + 2].toInt() and 0xff) shl 16) or
+ ((px[j + 1].toInt() and 0xff) shl 8) or (px[j].toInt() and 0xff)
+ }
+ val img = BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB_PRE)
+ img.raster.setDataElements(0, 0, size, size, argb)
+ ImageIO.write(img, "png", out)
+ println("wrote $out, ${argb.count { (it ushr 24) != 0 }} of ${argb.size} pixels drawn")
+ r.stop()
+ exitProcess(0)
+}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/ChatScreen.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/ChatScreen.kt
index 728033b..8e01500 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/ChatScreen.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/ChatScreen.kt
@@ -79,6 +79,11 @@ fun ChatScreen(onOpenSettings: () -> Unit) {
}
LaunchedEffect(rows.size) { if (rows.isNotEmpty()) list.animateScrollToItem(rows.size - 1) }
+ // The ball is the phone's way in: a tap talks, a second tap says "done".
+ fun toggleMic() {
+ if (!net.kuafuai.andee.desktop.voice.MacVoice.toggle()) progress = noVoiceKey()
+ }
+
fun send() {
val t = input.trim()
if (t.isEmpty() || busy) return
@@ -95,12 +100,7 @@ fun ChatScreen(onOpenSettings: () -> Unit) {
Spacer(Modifier.width(8.dp))
}
val listening = voice == net.kuafuai.andee.desktop.voice.MacVoice.State.LISTENING
- Pill(if (listening) (if (Strings.lang() == "zh") "● 说完了" else "● Done") else "🎤") {
- val v = net.kuafuai.andee.desktop.voice.MacVoice
- if (!v.configured()) {
- progress = if (Strings.lang() == "zh") "还没配语音 Key:在 ⚙ 设置的「语音」里填上。" else "No voice key yet: add it under Voice in ⚙ Settings."
- } else if (v.isListening()) v.stopListening() else v.startListening()
- }
+ Pill(if (listening) (if (Strings.lang() == "zh") "● 说完了" else "● Done") else "🎤") { toggleMic() }
Spacer(Modifier.width(8.dp))
Pill("⚙") { onOpenSettings() }
}
@@ -147,6 +147,9 @@ fun ChatScreen(onOpenSettings: () -> Unit) {
}
}
+fun noVoiceKey() =
+ if (Strings.lang() == "zh") "还没配语音 Key:在 ⚙ 设置的「语音」里填上。" else "No voice key yet: add it under Voice in ⚙ Settings."
+
@Composable
private fun Bubble(r: Scrollback.Row) {
val mine = r.role == Scrollback.Role.USER
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt
index 4fb14a6..b537af4 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt
@@ -96,6 +96,11 @@ class DesktopBrainHost(
TurnGuards.check(method, silent, untrusted)
val p = providers.firstOrNull { it.handles(method) }
?: throw IllegalArgumentException("unknown method $method")
+ // The phone nods for every `screen.*` call: a hand moved. On the Mac the
+ // terminal and the device tools are hands too; the notebook is not.
+ if (!silent && (method.startsWith("screen.") || method.startsWith("shell.") || method.startsWith("device."))) {
+ MacBall.onTool()
+ }
return p.dispatch(method, params, silent, untrusted)
}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopGl.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopGl.kt
new file mode 100644
index 0000000..458416a
--- /dev/null
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopGl.kt
@@ -0,0 +1,133 @@
+package net.kuafuai.andee.desktop
+
+import net.kuafuai.andee.ui.ball.gl.GlBackend
+import org.lwjgl.opengl.GL11
+import org.lwjgl.opengl.GL15
+import org.lwjgl.opengl.GL20
+import java.nio.Buffer
+
+/**
+ * The shared ball renderer's GL calls, on desktop OpenGL through LWJGL.
+ *
+ * Compiles its shader sources as GLSL ES 100 but wraps them for desktop GL 2.1;
+ * see [adaptShader]. Everything else is straight-through: the subset used by the
+ * renderer (`TRIANGLES`, array buffers, plain 4x4 matrix uniforms, alpha blend)
+ * runs unchanged whether it came from `android.opengl.GLES20` or `org.lwjgl.opengl`.
+ *
+ * Not thread-safe: only call from the render thread that owns the GL context.
+ */
+object DesktopGl : GlBackend {
+ // Pass-through GL 2.0 / ES 2.0 calls
+ override fun glAttachShader(program: Int, shader: Int) = GL20.glAttachShader(program, shader)
+ override fun glBindBuffer(target: Int, buffer: Int) = GL15.glBindBuffer(target, buffer)
+ override fun glBlendFunc(s: Int, d: Int) = GL11.glBlendFunc(s, d)
+ override fun glBufferData(target: Int, size: Int, data: Buffer?, usage: Int) {
+ // LWJGL has per-type overloads and infers size from remaining().
+ if (data == null) {
+ GL15.glBufferData(target, size.toLong(), usage)
+ return
+ }
+ require(data.remaining() * elementSize(data) == size) {
+ "glBufferData: size=$size but buffer.remaining()=${data.remaining()}"
+ }
+ when (data) {
+ is java.nio.ByteBuffer -> GL15.glBufferData(target, data, usage)
+ is java.nio.ShortBuffer -> GL15.glBufferData(target, data, usage)
+ is java.nio.IntBuffer -> GL15.glBufferData(target, data, usage)
+ is java.nio.FloatBuffer -> GL15.glBufferData(target, data, usage)
+ else -> throw IllegalArgumentException("glBufferData: unsupported ${data.javaClass.simpleName}")
+ }
+ }
+ override fun glBufferSubData(target: Int, offset: Int, size: Int, data: Buffer) {
+ val elemSize = elementSize(data)
+ require(data.remaining() * elemSize == size) {
+ "glBufferSubData: size=$size but buffer.remaining()=${data.remaining()}"
+ }
+ when (data) {
+ is java.nio.ByteBuffer -> GL15.glBufferSubData(target, offset.toLong(), data)
+ is java.nio.ShortBuffer -> GL15.glBufferSubData(target, offset.toLong(), data)
+ is java.nio.IntBuffer -> GL15.glBufferSubData(target, offset.toLong(), data)
+ is java.nio.FloatBuffer -> GL15.glBufferSubData(target, offset.toLong(), data)
+ else -> throw IllegalArgumentException("glBufferSubData: unsupported ${data.javaClass.simpleName}")
+ }
+ }
+ private fun elementSize(buf: Buffer) = when (buf) {
+ is java.nio.ByteBuffer -> 1
+ is java.nio.ShortBuffer -> 2
+ is java.nio.IntBuffer -> 4
+ is java.nio.FloatBuffer -> 4
+ is java.nio.DoubleBuffer -> 8
+ else -> throw IllegalArgumentException("Unknown buffer type: ${buf.javaClass.simpleName}")
+ }
+ override fun glClear(mask: Int) = GL11.glClear(mask)
+ override fun glClearColor(r: Float, g: Float, b: Float, a: Float) = GL11.glClearColor(r, g, b, a)
+ override fun glCompileShader(shader: Int) = GL20.glCompileShader(shader)
+ override fun glCreateProgram(): Int = GL20.glCreateProgram()
+ override fun glCreateShader(type: Int): Int = GL20.glCreateShader(type)
+ override fun glDeleteProgram(program: Int) = GL20.glDeleteProgram(program)
+ override fun glDeleteShader(shader: Int) = GL20.glDeleteShader(shader)
+ override fun glDepthMask(flag: Boolean) = GL11.glDepthMask(flag)
+ override fun glDisable(cap: Int) = GL11.glDisable(cap)
+ override fun glDrawArrays(mode: Int, first: Int, count: Int) = GL11.glDrawArrays(mode, first, count)
+ override fun glDrawElements(mode: Int, count: Int, type: Int, offset: Int) = GL11.glDrawElements(mode, count, type, offset.toLong())
+ override fun glEnable(cap: Int) = GL11.glEnable(cap)
+ override fun glEnableVertexAttribArray(index: Int) = GL20.glEnableVertexAttribArray(index)
+ override fun glGenBuffers(n: Int, out: IntArray, offset: Int) {
+ for (i in 0 until n) out[offset + i] = GL15.glGenBuffers()
+ }
+ override fun glGetAttribLocation(program: Int, name: String): Int = GL20.glGetAttribLocation(program, name)
+ override fun glGetProgramInfoLog(program: Int): String = GL20.glGetProgramInfoLog(program)
+ override fun glGetProgramiv(program: Int, pname: Int, out: IntArray, offset: Int) {
+ out[offset] = GL20.glGetProgrami(program, pname)
+ }
+ override fun glGetShaderInfoLog(shader: Int): String = GL20.glGetShaderInfoLog(shader)
+ override fun glGetShaderiv(shader: Int, pname: Int, out: IntArray, offset: Int) {
+ out[offset] = GL20.glGetShaderi(shader, pname)
+ }
+ override fun glGetUniformLocation(program: Int, name: String): Int = GL20.glGetUniformLocation(program, name)
+ override fun glLinkProgram(program: Int) = GL20.glLinkProgram(program)
+ override fun glScissor(x: Int, y: Int, w: Int, h: Int) = GL11.glScissor(x, y, w, h)
+ override fun glShaderSource(shader: Int, src: String) = GL20.glShaderSource(shader, src)
+ override fun glUniform1f(loc: Int, v: Float) = GL20.glUniform1f(loc, v)
+ override fun glUniform3fv(loc: Int, count: Int, v: FloatArray, offset: Int) {
+ GL20.glUniform3fv(loc, slice(v, offset, count * 3))
+ }
+ override fun glUniformMatrix4fv(loc: Int, count: Int, transpose: Boolean, v: FloatArray, offset: Int) {
+ GL20.glUniformMatrix4fv(loc, transpose, slice(v, offset, count * 16))
+ }
+ /** Android's (array, offset, count) as the exact span LWJGL infers its count from. */
+ private fun slice(v: FloatArray, offset: Int, n: Int): FloatArray =
+ if (offset == 0 && v.size == n) v else v.copyOfRange(offset, offset + n)
+
+ override fun glUseProgram(program: Int) = GL20.glUseProgram(program)
+ override fun glVertexAttribPointer(index: Int, size: Int, type: Int, normalized: Boolean, stride: Int, offset: Int) =
+ GL20.glVertexAttribPointer(index, size, type, normalized, stride, offset.toLong())
+ override fun glViewport(x: Int, y: Int, w: Int, h: Int) = GL11.glViewport(x, y, w, h)
+
+ /**
+ * Rewrites a mobile-side GLSL ES shader to run on desktop GL.
+ *
+ * The renderer's shaders target ES 2.0 (precision, `gl_PointCoord`, the ES
+ * 100 `varying`/`attribute` syntax) but this Mac's drivers expose GL 2.1
+ * with GLSL 1.20. Desktop GL demands `#version 120` in the source and does
+ * not understand `precision`. It *does* accept ES-style `attribute` as an
+ * alias for `in` and `varying` as an alias for out/in the way ES accepted
+ * them in 100 (before GLSL 3.00 forced `in`/`out` everywhere), which means
+ * the body code runs unchanged. `gl_PointCoord` works in both.
+ */
+ override fun adaptShader(src: String, fragment: Boolean): String = buildString {
+ append("#version 120\n")
+ var inBlock = false
+ src.lineSequence().forEach { line ->
+ val trimmed = line.trim()
+ if (trimmed.startsWith("/*")) inBlock = true
+ val inComment = inBlock || trimmed.startsWith("//") || trimmed.startsWith("*")
+ when {
+ trimmed.startsWith("precision") -> Unit // strip
+ inComment -> appendLine(line)
+ else -> appendLine(line)
+ }
+ if (trimmed.endsWith("*/")) inBlock = false
+ }
+ }
+}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/FloatingBall.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/FloatingBall.kt
new file mode 100644
index 0000000..6c8ef7a
--- /dev/null
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/FloatingBall.kt
@@ -0,0 +1,98 @@
+package net.kuafuai.andee.desktop
+
+import androidx.compose.foundation.gestures.detectDragGestures
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.unit.DpSize
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.window.ApplicationScope
+import androidx.compose.ui.window.Window
+import androidx.compose.ui.window.WindowPosition
+import androidx.compose.ui.window.rememberWindowState
+import kotlinx.coroutines.delay
+import java.awt.GraphicsEnvironment
+
+/** The ball's window title; the native side finds the window by it. */
+const val BALL_TITLE = "Andee Ball"
+
+private val BALL_WINDOW = 112.dp
+
+/**
+ * The ball, floating above every app the way the phone's overlay floats above
+ * every app: borderless, transparent, never takes focus, on every Space and
+ * over full-screen apps (that last part is the native `floatWindow`, because a
+ * JVM's "always on top" is only the floating level on the current Space).
+ *
+ * Tap talks, as on the phone. Long-press shows or hides the chat window — the
+ * phone's long-press unfolds the card. Quitting is ⌘Q, since closing the chat only hides it. Drag moves it, and where it was left is
+ * remembered.
+ */
+@Composable
+fun ApplicationScope.FloatingBall(onTap: () -> Unit, onLongPress: () -> Unit, onWindow: (java.awt.Window) -> Unit) {
+ val state = rememberWindowState(size = DpSize(BALL_WINDOW, BALL_WINDOW), position = savedPosition())
+ Window(
+ onCloseRequest = ::exitApplication,
+ state = state,
+ title = BALL_TITLE,
+ undecorated = true,
+ transparent = true,
+ resizable = false,
+ alwaysOnTop = true,
+ focusable = false,
+ ) {
+ val w = window
+ onWindow(w)
+ LaunchedEffect(Unit) {
+ // The native window exists once AWT has shown it; ask until it has.
+ repeat(20) {
+ if (w.isShowing && net.kuafuai.andee.desktop.mac.Bridge.floatWindow(BALL_TITLE)) return@LaunchedEffect
+ delay(100)
+ }
+ }
+ Box(
+ Modifier.fillMaxSize()
+ .pointerInput(Unit) {
+ // Follow the mouse on the *screen*, not the pointer's offset inside
+ // the window: the window moves under the pointer with every step, so
+ // window-relative deltas half-cancel each other and the ball shudders.
+ var grab = java.awt.Point()
+ var origin = java.awt.Point()
+ detectDragGestures(
+ onDragStart = {
+ grab = java.awt.MouseInfo.getPointerInfo().location
+ origin = w.location
+ },
+ onDragEnd = { Settings.save(mapOf("ball_pos" to "${w.x},${w.y}")) },
+ ) { change, _ ->
+ change.consume()
+ val now = java.awt.MouseInfo.getPointerInfo().location
+ w.setLocation(origin.x + now.x - grab.x, origin.y + now.y - grab.y)
+ }
+ }
+ .pointerInput(Unit) {
+ detectTapGestures(onTap = { onTap() }, onLongPress = { onLongPress() })
+ },
+ contentAlignment = Alignment.Center,
+ ) {
+ BallView(BALL_WINDOW, onClick = null)
+ }
+ }
+}
+
+/** Where the user left it; bottom-right of the main screen the first time. */
+private fun savedPosition(): WindowPosition {
+ Settings.get("ball_pos").split(',').mapNotNull { it.trim().toIntOrNull() }.takeIf { it.size == 2 }?.let { (x, y) ->
+ val onScreen = GraphicsEnvironment.getLocalGraphicsEnvironment().screenDevices
+ .any { it.defaultConfiguration.bounds.contains(x + 40, y + 40) }
+ if (onScreen) return WindowPosition(x.dp, y.dp)
+ }
+ val b = GraphicsEnvironment.getLocalGraphicsEnvironment().maximumWindowBounds
+ return WindowPosition((b.x + b.width - 112 - 24).dp, (b.y + b.height - 112 - 24).dp)
+}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/MacBall.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/MacBall.kt
new file mode 100644
index 0000000..3fe538d
--- /dev/null
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/MacBall.kt
@@ -0,0 +1,148 @@
+package net.kuafuai.andee.desktop
+
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.layout.size
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.asComposeImageBitmap
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.IntSize
+import net.kuafuai.andee.brain.SpeechMood
+import net.kuafuai.andee.desktop.voice.MacVoice
+import net.kuafuai.andee.ui.ball.Action
+import net.kuafuai.andee.ui.ball.BallLooks
+import net.kuafuai.andee.ui.ball.Mood
+import org.jetbrains.skia.ColorAlphaType
+import org.jetbrains.skia.ColorType
+import org.jetbrains.skia.Bitmap
+import org.jetbrains.skia.ImageInfo
+
+/**
+ * The ball's face on the Mac, decided the way the phone's FloatingWindowUi
+ * decides it: the voice pipeline's state, a task in progress, a nod per tool
+ * call, a pop when an answer lands, and the face the model picked for what it
+ * is saying. Everything here is a fact about Andee; [BallView] only paints.
+ *
+ * State lives here rather than in the renderer so a renderer that comes and
+ * goes with the window (or never starts, on a Mac with no OpenGL) loses nothing.
+ */
+object MacBall {
+
+ @Volatile private var renderer: BallRenderer? = null
+ @Volatile private var voice = MacVoice.State.IDLE
+ @Volatile private var busy = false
+ @Volatile private var emotion: Mood? = null
+
+ /** The face the model asked for in the reply about to be spoken. */
+ @Volatile private var nextEmotion: Mood? = null
+
+ /** Restores the saved look; by name, like the phone's `ball` key. */
+ fun restoreLook() = BallLooks.requestByName(Settings.get("ball").ifEmpty { null })
+
+ /** Switch to another character and remember it. */
+ fun pickLook(name: String) {
+ BallLooks.requestByName(name)
+ Settings.save(mapOf("ball" to name))
+ renderer?.trigger(Action.POP)
+ }
+
+ fun onVoice(s: MacVoice.State) {
+ val was = voice
+ voice = s
+ // The model's face belongs to one utterance (see FloatingWindowUi.setState).
+ emotion = if (s == MacVoice.State.SPEAKING) nextEmotion else null
+ if (s == MacVoice.State.LISTENING && was != s) renderer?.trigger(Action.HOP)
+ apply()
+ }
+
+ fun onBusy(b: Boolean) {
+ busy = b
+ apply()
+ }
+
+ /** A tool ran: a nod, then back to the working face on its own. */
+ fun onTool() { renderer?.pulseTool() }
+
+ /**
+ * An answer came back. The opening face it was written with is held for
+ * when (if) it is spoken — the phone's fallback when the cue clock is
+ * unknown, and on the Mac it always is. Then the pop: the same overclaim
+ * the phone's `endTask` makes, for the same reason.
+ */
+ fun onAnswer(raw: String) {
+ nextEmotion = SpeechMood.parse(raw).cues.firstOrNull()?.mood
+ renderer?.signalOutcome(true)
+ }
+
+ internal fun attach(r: BallRenderer) {
+ renderer = r
+ apply()
+ }
+
+ internal fun detach(r: BallRenderer) {
+ if (renderer === r) renderer = null
+ }
+
+ private fun apply() {
+ val r = renderer ?: return
+ val mood = when {
+ voice == MacVoice.State.LISTENING -> Mood.LISTENING
+ voice == MacVoice.State.SPEAKING -> Mood.SPEAKING
+ busy -> Mood.THINKING
+ else -> Mood.CALM
+ }
+ r.setState(mood, listening = mood == Mood.LISTENING, emotion = emotion)
+ r.setWorking(busy)
+ }
+}
+
+/**
+ * The ball, [size] across, painted from [BallRenderer]'s frames at the
+ * display's own rate. Rendered at device pixels so it is sharp on Retina.
+ * A Mac where OpenGL cannot be had simply shows no ball.
+ */
+@Composable
+fun BallView(size: Dp, onClick: (() -> Unit)?, modifier: Modifier = Modifier) {
+ val px = with(LocalDensity.current) { size.roundToPx() }
+ val renderer = remember(px) { BallRenderer(px, px) }
+ DisposableEffect(renderer) {
+ MacBall.attach(renderer)
+ onDispose { MacBall.detach(renderer); renderer.stop() }
+ }
+ // One bitmap for the life of the view, refilled in place; a new image per
+ // frame was most of the app's CPU. Redraws are pushed by the render thread,
+ // so nothing here runs between frames.
+ val bitmap = remember(px) {
+ Bitmap().apply { allocPixels(ImageInfo(px, px, ColorType.BGRA_8888, ColorAlphaType.PREMUL)) }
+ }
+ val image = remember(bitmap) { bitmap.asComposeImageBitmap() }
+ var tick by remember { mutableStateOf(0) }
+ DisposableEffect(renderer) {
+ // At most one repaint queued: a busy UI thread (a drag) skips frames instead of piling them up.
+ val queued = java.util.concurrent.atomic.AtomicBoolean(false)
+ renderer.onFrame = {
+ if (queued.compareAndSet(false, true)) javax.swing.SwingUtilities.invokeLater {
+ queued.set(false)
+ renderer.frame?.let { f -> bitmap.installPixels(f); bitmap.notifyPixelsChanged(); tick++ }
+ }
+ }
+ onDispose { renderer.onFrame = {} }
+ }
+ val click = if (onClick == null) Modifier else Modifier.clickable(
+ interactionSource = remember { MutableInteractionSource() },
+ indication = null,
+ onClick = onClick,
+ )
+ Canvas(modifier.size(size).then(click)) {
+ if (tick > 0) drawImage(image, dstOffset = IntOffset.Zero, dstSize = IntSize(this.size.width.toInt(), this.size.height.toInt()))
+ }
+}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt
index 9327805..8bb2632 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt
@@ -6,6 +6,7 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
+import androidx.compose.ui.window.MenuBar
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
import java.io.File
@@ -17,20 +18,39 @@ fun main() {
installFileLog()
net.kuafuai.andee.util.Log.i("Andee", "starting, data in ${AppDirs.root}")
Assistant.askApproval = { ApprovalGate.request(it) }
+ MacBall.restoreLook()
Assistant.start()
application {
var settings by remember { mutableStateOf(false) }
var pending by remember { mutableStateOf(ApprovalGate.current) }
- ApprovalGate.onChange = { pending = ApprovalGate.current }
+ // The chat is the phone's unfolded card: the ball is always there, the chat comes and goes.
+ var chat by remember { mutableStateOf(true) }
+ ApprovalGate.onChange = { pending = ApprovalGate.current; if (pending != null) chat = true }
+ var ballWindow by remember { mutableStateOf<java.awt.Window?>(null) }
+ var chatWindow by remember { mutableStateOf<java.awt.Window?>(null) }
+ // A click aimed at another app must not land on Andee: both windows step aside for the instant of it.
+ // (Native, not Window.opacity: AWT refuses that on the decorated chat window.)
+ Assistant.hideWindows = { hide -> net.kuafuai.andee.desktop.mac.Bridge.setOwnAlpha(if (hide) 0.0 else 1.0) }
+
+ FloatingBall(
+ onTap = { if (!net.kuafuai.andee.desktop.voice.MacVoice.toggle()) { chat = true; settings = true } },
+ onLongPress = { chat = !chat },
+ onWindow = { ballWindow = it },
+ )
+
Window(
- onCloseRequest = ::exitApplication,
+ onCloseRequest = { chat = false },
+ visible = chat,
title = "Andee",
state = rememberWindowState(width = 520.dp, height = 760.dp),
) {
- // A click aimed at another app must not land on Andee: step aside for the instant of it.
- val w = this.window
- Assistant.hideWindows = { hide ->
- javax.swing.SwingUtilities.invokeAndWait { w.opacity = if (hide) 0f else 1f }
+ chatWindow = window
+ MenuBar {
+ Menu("Andee") {
+ Item(if (Strings.lang() == "zh") "显示对话" else "Show chat", onClick = { chat = true })
+ Item(if (Strings.lang() == "zh") "退出 Andee" else "Quit Andee", onClick = ::exitApplication,
+ shortcut = androidx.compose.ui.input.key.KeyShortcut(androidx.compose.ui.input.key.Key.Q, meta = true))
+ }
}
androidx.compose.foundation.layout.Box {
if (settings) SettingsScreen { settings = false } else ChatScreen { settings = true }
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Settings.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Settings.kt
index a39dfae..63efde3 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Settings.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Settings.kt
@@ -30,7 +30,7 @@ object Settings {
val KEYS = setOf(
"brain", "llm_api_key", "llm_base_url", "llm_model", "llm_thinking", "llm_reasoning_effort",
"api_key", "asr_endpoint", "tts_endpoint", "asr_resource_id", "tts_resource_id", "tts_speaker",
- "voice_provider", "lang", "max_steps", "scene", "ball",
+ "voice_provider", "lang", "max_steps", "scene", "ball", "ball_pos",
"shell_mode", "shell_workdirs", "shell_critical_confirm",
)
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt
index 579586b..4072971 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt
@@ -52,6 +52,12 @@ fun SettingsScreen(onDone: () -> Unit) {
Section(t("界面语言", "Language"))
Picker(listOf("zh" to "中", "en" to "EN"), lang) { lang = it; v["lang"] = it }
+ Section(t("形象", "Look"))
+ Picker(
+ net.kuafuai.andee.ui.ball.BallLooks.ALL.map { it.name to Strings.get("ball_look_${it.name}") },
+ v["ball"].orEmpty().ifEmpty { net.kuafuai.andee.ui.ball.BallLooks.ALL.first().name },
+ ) { v["ball"] = it }
+
Section(t("后端", "Backend"))
Picker(
listOf("local" to t("本机(自己的 Key)", "Own key"), "codeflying" to "CodeFlying"),
@@ -103,6 +109,7 @@ fun SettingsScreen(onDone: () -> Unit) {
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Pill(t("保存", "Save")) {
Settings.save(v.toMap())
+ v["ball"]?.let { MacBall.pickLook(it) }
Thread { Assistant.ensure() }.start()
onDone()
}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt
index 79b1edf..175b6bc 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt
@@ -32,6 +32,9 @@ object Bridge {
fun andee_key(keyCode: Int, flags: Int)
fun andee_screenshot(path: String, maxSide: Int): Int
fun andee_open(target: String): Int
+ fun andee_float_window(title: String): Int
+ fun andee_set_own_alpha(alpha: Double): Int
+ fun andee_own_window_at(x: Double, y: Double): Int
}
private val lib: Lib? by lazy {
@@ -79,6 +82,14 @@ object Bridge {
fun key(code: Int, flags: Int = 0) = need().andee_key(code, flags)
fun screenshot(path: String, maxSide: Int) = need().andee_screenshot(path, maxSide) == 1
fun open(target: String) = need().andee_open(target) == 1
+ /** See andee_float_window: above every app, on every Space. False if the bridge or the window is missing. */
+ fun floatWindow(title: String) = lib?.andee_float_window(title) == 1
+ /** Every Andee window to [alpha] (0 = stepped aside for a click). */
+ fun setOwnAlpha(alpha: Double) = lib?.andee_set_own_alpha(alpha) == 1
+
+ /** True when one of Andee's visible windows covers (x, y); unknown counts as yes. */
+ fun ownWindowAt(x: Double, y: Double) = lib?.andee_own_window_at(x, y) != 0
+
/** macOS virtual key codes the tools use. */
object Keys {
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacDevice.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacDevice.kt
index cee0edd..405548f 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacDevice.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacDevice.kt
@@ -212,8 +212,11 @@ class MacDevice : DesktopBrainHost.ToolProvider {
(if (Bridge.axTrusted()) granted else missing).put(JSONObject().put("id", "accessibility").put("feature", "operate other apps"))
(if (Bridge.screenCaptureAllowed()) granted else missing).put(JSONObject().put("id", "screen_recording").put("feature", "see the screen"))
return JSONObject().put("granted", granted).put("missing", missing)
- .put("note", "Calendar, Reminders and Contacts ask for permission the first time they are used. " +
- "Missing ones are granted in System Settings → Privacy & Security; Andee's ✓ check card has buttons.")
+ .put("note", "Calendar, Reminders and Contacts ask for permission the first time they are used.")
+ .also { o ->
+ if (!Bridge.axTrusted()) o.put("accessibility_fix", PermissionHelp.ACCESSIBILITY)
+ if (!Bridge.screenCaptureAllowed()) o.put("screen_recording_fix", PermissionHelp.SCREEN_RECORDING)
+ }
}
// ---- helpers --------------------------------------------------------------
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacScreen.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacScreen.kt
index 0341da2..40b178d 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacScreen.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacScreen.kt
@@ -42,10 +42,7 @@ class MacScreen(
override fun dispatch(method: String, p: JSONObject, silent: Boolean, untrusted: Boolean): Any? {
if (!Bridge.available) throw IllegalStateException("The Mac screen bridge did not load; screen tools cannot run here.")
- if (!Bridge.axTrusted()) throw IllegalStateException(
- "Andee does not have Accessibility permission on this Mac, so it cannot read or operate the screen. " +
- "Tell the user to allow it in System Settings → Privacy & Security → Accessibility (Andee's ✓ check card has a button).",
- )
+ if (!Bridge.axTrusted()) throw IllegalStateException(PermissionHelp.ACCESSIBILITY)
return when (method) {
"screen.ui_tree" -> uiTree(p.optBoolean("with_shot", false))
"screen.tap_id" -> tapId(req(p, "eid"), long = false)
@@ -139,8 +136,9 @@ class MacScreen(
"unknown element $eid — the screen has changed or the number is from an older list. Re-dump with get_screen_element; do not guess.",
)
val (nx, ny) = toNorm(e.cx, e.cy)
- val pressed = !long && e.press && gesture { Bridge.axPressAt(e.cx, e.cy) }
- if (!pressed) gesture { Bridge.click(e.cx, e.cy, right = long, holdMs = 40) }
+ // A Press action is not a pointer event and the hit test already skips our windows: nothing to step aside for.
+ val pressed = !long && e.press && Bridge.axPressAt(e.cx, e.cy)
+ if (!pressed) gesture(e.cx, e.cy) { Bridge.click(e.cx, e.cy, right = long, holdMs = 40) }
return afterTap(JSONObject().put("completed", true).put("eid", eid).put("label", e.label)
.put("via", if (pressed) "press_action" else if (long) "right_click" else "click").put("x", nx).put("y", ny))
}
@@ -149,7 +147,7 @@ class MacScreen(
val (nx, ny, label) = resolveAim(p)
guardSpot(nx, ny)
val (x, y) = toPx(nx, ny)
- gesture { Bridge.click(x, y, right = long, holdMs = if (long) 40 else 40) }
+ gesture(x, y) { Bridge.click(x, y, right = long, holdMs = 40) }
return afterTap(JSONObject().put("completed", true).put("x", nx).put("y", ny).put("aimed_at", label)
.put("via", if (long) "right_click" else "click"))
}
@@ -223,7 +221,7 @@ class MacScreen(
listOf(x1 to "x1", y1 to "y1", x2 to "x2", y2 to "y2").forEach { requireNorm(it.first, it.second) }
val (ax, ay) = toPx(x1, y1); val (bx, by) = toPx(x2, y2)
// On a Mac a swipe that scrolls is a scroll: the content moves the way the finger did, by that distance.
- gesture { Bridge.scroll(ax, ay, (bx - ax).toInt(), (by - ay).toInt()) }
+ gesture(ax, ay) { Bridge.scroll(ax, ay, (bx - ax).toInt(), (by - ay).toInt()) }
return JSONObject().put("completed", true).put("from", "$x1,$y1").put("to", "$x2,$y2").put("via", "scroll")
.put("note", "A swipe scrolls whatever is under the start point by that distance. To drag something, use the app's own controls.")
}
@@ -232,7 +230,8 @@ class MacScreen(
val before = Bridge.focusedValue()
if (!before.optBoolean("focused")) throw IllegalStateException("no field has focus — click into the field first")
val viaAx = Bridge.setFocusedValue(text)
- if (!viaAx) gesture { Bridge.key(Bridge.Keys.A, Bridge.Keys.CMD); Bridge.key(Bridge.Keys.DELETE); Bridge.typeText(text) }
+ // Keys go to the focused app, not to a point on screen: fading our windows changes nothing for them.
+ if (!viaAx) { Bridge.key(Bridge.Keys.A, Bridge.Keys.CMD); Bridge.key(Bridge.Keys.DELETE); Bridge.typeText(text) }
Thread.sleep(150)
val now = Bridge.focusedValue().optString("value")
val ok = now == text || now.contains(text)
@@ -241,7 +240,7 @@ class MacScreen(
}
private fun submit(): JSONObject {
- gesture { Bridge.key(Bridge.Keys.RETURN) }
+ Bridge.key(Bridge.Keys.RETURN)
return JSONObject().put("performed", true).put("via", "return_key")
}
@@ -275,17 +274,18 @@ class MacScreen(
return JSONObject().put("png_base64", shot(grid)).put("aim_grid", AIM_GRID_NOTE)
}
- private fun capture(): BufferedImage {
+ /** [maxSide] is the size wanted, so a plain shot is not captured at 2560 to be shrunk to 1280 again. */
+ private fun capture(maxSide: Int = 2560): BufferedImage {
val f = File.createTempFile("andee-shot", ".png")
try {
- val ok = gestureless { Bridge.screenshot(f.path, 2560) }
+ val ok = gestureless { Bridge.screenshot(f.path, maxSide) }
if (!ok) throw IllegalStateException(SCREEN_RECORDING_NOTE)
return ImageIO.read(f)
} finally { f.delete() }
}
private fun shot(grid: Boolean): String {
- var img = capture()
+ var img = capture(SHOT_MAX_SIDE)
img = scale(img, SHOT_MAX_SIDE)
if (grid) drawGrid(img, zoom = false)
return png(img)
@@ -377,9 +377,23 @@ class MacScreen(
// ---- our own windows -----------------------------------------------------
/** Gestures hide our windows so a click cannot land on Andee. */
- private fun <T> gesture(block: () -> T): T {
- hideOwnWindows(true)
- try { Thread.sleep(120); return block() } finally { hideOwnWindows(false) }
+ /**
+ * A pointer event at (x, y): step aside only if one of our windows is
+ * actually there. Hiding for every click cost ~150 ms a tap and made the
+ * ball blink each time the brain touched anything anywhere on the screen.
+ */
+ private fun <T> gesture(x: Double, y: Double, block: () -> T): T =
+ if (Bridge.ownWindowAt(x, y)) stepAside(block) else block()
+
+ private fun <T> stepAside(block: () -> T): T {
+ // The hide is inside the try: if it fails half-way, the windows must still come back.
+ try {
+ runCatching { hideOwnWindows(true) }.onFailure { net.kuafuai.andee.util.Log.w("MacScreen", "could not step aside", it) }
+ Thread.sleep(60) // the alpha change is applied synchronously; one or two frames for the window server
+ return block()
+ } finally {
+ runCatching { hideOwnWindows(false) }.onFailure { net.kuafuai.andee.util.Log.e("MacScreen", "could not come back", it) }
+ }
}
/** Captures exclude our process in ScreenCaptureKit itself; nothing to hide. */
@@ -399,10 +413,7 @@ class MacScreen(
"screen.screenshot", "screen.global",
)
- const val SCREEN_RECORDING_NOTE =
- "Andee does not have Screen Recording permission on this Mac, so it cannot see the screen. Tell the user to " +
- "allow it in System Settings → Privacy & Security → Screen & System Audio Recording (the ✓ check card has a button), " +
- "then quit and reopen Andee."
+ val SCREEN_RECORDING_NOTE: String get() = PermissionHelp.SCREEN_RECORDING
private const val AIM_GRID_NOTE =
"This image carries an 8x12 aim grid, A1 (top-left) to H12 (bottom-right), each label at the centre of its cell. " +
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/PermissionHelp.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/PermissionHelp.kt
new file mode 100644
index 0000000..277ae79
--- /dev/null
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/PermissionHelp.kt
@@ -0,0 +1,41 @@
+package net.kuafuai.andee.desktop.mac
+
+import java.io.File
+
+/**
+ * What to tell the user when a macOS privacy permission is missing.
+ *
+ * The usual cause is not that the user never turned it on. macOS remembers the
+ * grant against the exact build of an ad-hoc-signed app, so every rebuilt
+ * Andee.app is a stranger to it: the switch in System Settings still shows *on*
+ * (for the old build) while this one is refused. Telling the user to "turn it on"
+ * sends them to a switch that already is — so the text says to remove the entry
+ * and add this copy back, and names which copy that is.
+ */
+object PermissionHelp {
+
+ /** The running Andee.app, for the user to pick in the "+" dialog; null under `gradle run`. */
+ fun appPath(): String? = System.getProperty("jpackage.app-path")
+ ?.let { File(it).parentFile?.parentFile?.parentFile } // …/Andee.app/Contents/MacOS/Andee
+ ?.takeIf { it.name.endsWith(".app") }?.path
+
+ private fun steps(pane: String): String {
+ val app = appPath()
+ val which = if (app != null) "this copy of Andee at $app" else "the Andee.app being run"
+ return "In System Settings → Privacy & Security → $pane: if Andee is not listed, click + and add $which, then switch it on. " +
+ "If Andee is already listed and switched on, that entry belongs to an earlier build (macOS ties the grant to the exact " +
+ "build, and every update counts as a new app): select Andee, click − to remove it, then click + and add $which, switch " +
+ "it on, and quit and reopen Andee (⌘Q). Do not just tell the user to turn it on — if they say it is already on, this " +
+ "remove-and-re-add is the fix. You can open the pane for them with run_command: open \"x-apple.systempreferences:" +
+ "com.apple.preference.security?${anchor(pane)}\"."
+ }
+
+ private fun anchor(pane: String) = if (pane == "Accessibility") "Privacy_Accessibility" else "Privacy_ScreenCapture"
+
+ val ACCESSIBILITY: String get() =
+ "Andee does not have Accessibility permission on this Mac, so it cannot read or operate the screen. " + steps("Accessibility")
+
+ val SCREEN_RECORDING: String get() =
+ "Andee does not have Screen Recording permission on this Mac, so it cannot see the screen. " +
+ steps("Screen & System Audio Recording")
+}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/voice/MacVoice.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/voice/MacVoice.kt
index 65044ee..63b78a4 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/voice/MacVoice.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/voice/MacVoice.kt
@@ -36,6 +36,12 @@ object MacVoice {
enum class State { IDLE, LISTENING, SPEAKING }
+ /** Every change goes to the ball as well as the window, which has its own listener slot. */
+ private fun state(s: State) {
+ net.kuafuai.andee.desktop.MacBall.onVoice(s)
+ onState(s)
+ }
+
private val io = Executors.newCachedThreadPool { r -> Thread(r, "voice").apply { isDaemon = true } }
private val listening = AtomicBoolean(false)
@Volatile private var mic: TargetDataLine? = null
@@ -78,7 +84,7 @@ object MacVoice {
val cfg = settings()
val engine: AsrEngine = if (cfg.voiceProvider == VoiceSettings.VOICE_GOOGLE) GoogleAsr(cfg, listener) else HuoshanAsr(cfg, listener)
asr = engine
- onState(State.LISTENING)
+ state(State.LISTENING)
io.execute {
runCatching {
engine.start(ASR_RATE, 1)
@@ -100,10 +106,17 @@ object MacVoice {
mic = null
runCatching { engine.close() }
if (asr === engine) asr = null
- onState(State.IDLE)
+ state(State.IDLE)
}
}
+ /** The ball's tap and the 🎤 button: start, or say "done". False when there is no voice key. */
+ fun toggle(): Boolean {
+ if (!configured()) return false
+ if (isListening()) stopListening() else startListening()
+ return true
+ }
+
fun stopListening() {
if (listening.compareAndSet(true, false)) asr?.endOfTurn(bySilence = false)
}
@@ -141,7 +154,7 @@ object MacVoice {
runCatching {
val fmt = AudioFormat(sampleRate.toFloat(), 16, 1, true, false)
speaker = AudioSystem.getSourceDataLine(fmt).apply { open(fmt, sampleRate * 2); start() }
- onState(State.SPEAKING)
+ state(State.SPEAKING)
}.onFailure { Log.e(TAG, "speaker unavailable", it) }
}
override fun onAudio(pcm: ByteArray) { speaker?.write(pcm, 0, pcm.size) }
@@ -155,7 +168,7 @@ object MacVoice {
io.execute {
runCatching { speaker?.drain(); speaker?.close() }
speaker = null
- onState(State.IDLE)
+ state(State.IDLE)
}
}
}
diff --git a/desktop/src/main/resources/strings_en.properties b/desktop/src/main/resources/strings_en.properties
index bb86bc3..0a634b9 100644
--- a/desktop/src/main/resources/strings_en.properties
+++ b/desktop/src/main/resources/strings_en.properties
@@ -31,3 +31,9 @@ NARRATE_DOG=Moving a leg…
NARRATE_MARKET_SEARCH=Finding a tool…
NARRATE_MARKET_CALL=Calling an external service…
NARRATE_DEFAULT=Running %1$s…
+ball_look_andee=Andee
+ball_look_cream=Cream
+ball_look_bajie=Pigsy
+ball_look_rabbit=Rascal
+ball_look_bear=Bear
+ball_look_imp=Imp
diff --git a/desktop/src/main/resources/strings_zh.properties b/desktop/src/main/resources/strings_zh.properties
index 4533be0..9bd6e43 100644
--- a/desktop/src/main/resources/strings_zh.properties
+++ b/desktop/src/main/resources/strings_zh.properties
@@ -31,3 +31,9 @@ NARRATE_DOG=动一下腿…
NARRATE_MARKET_SEARCH=找工具…
NARRATE_MARKET_CALL=调用外部服务…
NARRATE_DEFAULT=正在 %1$s…
+ball_look_andee=Andee
+ball_look_cream=奶油
+ball_look_bajie=八戒
+ball_look_rabbit=贱贱兔
+ball_look_bear=憨憨熊
+ball_look_imp=小恶魔