feat: 初始化跨平台远程编译服务与 Android Studio 插件

This commit is contained in:
tongtong committed 2026-11-24 14:46:34 +08:00
commit 9eba4556db
44 files changed
+2802

No files matched your search

@@ -0,0 +1,53 @@
package studio.tongtong.remotecompile
import java.nio.file.Files
import java.nio.file.Path
import java.util.Properties
import java.util.concurrent.TimeUnit
data class AdbDevice(val serial: String, val state: String, val model: String) {
val online get() = state == "device"
override fun toString(): String {
val label = when (state) { "device" -> if (serial.startsWith("emulator-")) "模拟器" else "已连接"; "unauthorized" -> "未授权,请在手机上确认"; "offline" -> "离线"; else -> state }
return "${model.ifBlank { serial }} · $label ($serial)"
}
}
object AdbDevices {
fun choose(devices: List<AdbDevice>, preferred: String, explicit: Boolean = false): AdbDevice? {
val online = devices.filter { it.online }
return online.firstOrNull { it.serial == preferred } ?: if (explicit) null else online.singleOrNull()
}
fun parse(output: String): List<AdbDevice> = output.lineSequence().map(String::trim)
.filter { it.isNotEmpty() && !it.startsWith("List of devices") && !it.startsWith("*") && !it.startsWith("adb:") }
.mapNotNull { line ->
val fields = line.split(Regex("\\s+"))
if (fields.size < 2 || fields[1] !in setOf("device", "offline", "unauthorized", "recovery", "sideload", "bootloader", "no")) null
else AdbDevice(fields[0], fields[1], fields.drop(2).firstOrNull { it.startsWith("model:") }?.removePrefix("model:")?.replace('_', ' ') ?: "")
}.distinctBy { it.serial }.toList()
fun resolve(source: Path, configured: String): String {
if (configured.isNotBlank() && configured != "adb") return configured
val properties = Properties()
val local = source.resolve("local.properties")
if (Files.isRegularFile(local)) Files.newInputStream(local).use(properties::load)
val roots = listOfNotNull(properties.getProperty("sdk.dir"), System.getenv("ANDROID_HOME"), System.getenv("ANDROID_SDK_ROOT"),
System.getenv("LOCALAPPDATA")?.let { "$it/Android/Sdk" },
System.getProperty("user.home")?.let { "$it/Library/Android/sdk" },
System.getProperty("user.home")?.let { "$it/Android/Sdk" })
val executable = if (System.getProperty("os.name").startsWith("Windows")) "adb.exe" else "adb"
return roots.map { Path.of(it).resolve("platform-tools").resolve(executable) }.firstOrNull { Files.isRegularFile(it) }?.toString() ?: "adb"
}
fun list(adb: String): List<AdbDevice> {
val log = Files.createTempFile("remotecompile-devices-", ".log")
try {
val process = ProcessBuilder(adb, "devices", "-l").redirectErrorStream(true).redirectOutput(log.toFile()).start()
try {
check(process.waitFor(15, TimeUnit.SECONDS)) { "读取设备超时" }
check(process.exitValue() == 0) { "adb 读取设备失败,请检查右侧配置中的 adb 路径" }
return parse(Files.readString(log))
} finally { if (process.isAlive) { process.destroyForcibly(); process.waitFor(3, TimeUnit.SECONDS) } }
} finally { Files.deleteIfExists(log) }
}
}
@@ -0,0 +1,256 @@
package studio.tongtong.remotecompile
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.Disposable
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.openapi.components.Service
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.content.ContentFactory
import java.awt.BorderLayout
import java.net.URI
import java.net.URLEncoder
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.nio.file.Files
import java.nio.file.Path
import java.security.MessageDigest
import java.time.Duration
import java.util.Base64
import java.util.UUID
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import javax.swing.*
@Service(Service.Level.PROJECT)
class PanelService(val project: Project) {
var panel: RemotePanel? = null
}
class RemoteToolWindow : ToolWindowFactory {
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
val panel = RemotePanel(project)
project.getService(PanelService::class.java).panel = panel
val content = ContentFactory.getInstance().createContent(panel, "构建日志", false)
content.setDisposer(panel)
toolWindow.contentManager.addContent(content)
}
}
class RemoteRunAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
ToolWindowManager.getInstance(project).getToolWindow("Remote Compilation")?.show {
project.getService(PanelService::class.java).panel?.runBuild()
}
}
}
class RemoteSettingsAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
e.project?.let { ToolWindowManager.getInstance(it).getToolWindow("Remote Configuration")?.show() }
}
}
class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Disposable {
private val settings = project.getService(Settings::class.java)
private val devices = JComboBox<AdbDevice>()
private val refresh = JButton("刷新设备")
private val deviceStatus = JLabel("正在读取本机设备…")
private val refreshing = AtomicBoolean(false)
private var updatingDevices = false
@Volatile private var disposed = false
private val run = JButton("Remote Run")
private val cancel = JButton("取消远程构建")
private val log = JTextArea().apply { isEditable = false }
@Volatile private var activeBuild = ""
@Volatile private var cancelRequested = false
@Volatile private var busy = false
private val gson = Gson()
private val http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(15)).build()
private val polling = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay({ refreshDevices() }, 1, 5, TimeUnit.SECONDS)
init {
val configure = JButton("连接设置")
val buttons = JPanel().apply { add(JLabel("目标设备")); add(devices); add(refresh); add(run); add(cancel); add(configure) }
val top = JPanel(BorderLayout()).apply { add(buttons, BorderLayout.CENTER); add(deviceStatus, BorderLayout.SOUTH) }
devices.prototypeDisplayValue = AdbDevice("serial", "device", "选择本机设备或模拟器")
devices.renderer = object : DefaultListCellRenderer() {
override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, selected: Boolean, focus: Boolean): java.awt.Component {
val component = super.getListCellRendererComponent(list, value ?: "请选择设备", index, selected, focus)
isEnabled = value !is AdbDevice || value.online
return component
}
}
devices.addActionListener { if (!updatingDevices) (devices.selectedItem as? AdbDevice)?.takeIf { it.online }?.let { settings.selectDevice(it.serial) } }
refresh.addActionListener { refreshDevices() }
configure.addActionListener { ToolWindowManager.getInstance(project).getToolWindow("Remote Configuration")?.show() }
add(top, BorderLayout.NORTH); add(JScrollPane(log), BorderLayout.CENTER)
run.addActionListener { runBuild() }
cancel.addActionListener { cancelRequested = true; append("已请求取消,等待当前网络操作结束…") }
}
override fun dispose() {
disposed = true; polling.cancel(false)
if (!project.isDisposed && project.getService(PanelService::class.java).panel === this) project.getService(PanelService::class.java).panel = null
}
fun refreshDevices() {
if (disposed || project.isDisposed || !refreshing.compareAndSet(false, true)) return
ApplicationManager.getApplication().executeOnPooledThread {
val cfg = settings.snapshot()
val result = runCatching { AdbDevices.list(AdbDevices.resolve(Path.of(project.basePath ?: error("项目路径不存在")), cfg.adb)) }
ApplicationManager.getApplication().invokeLater {
try {
if (!disposed && !project.isDisposed) {
val found = result.getOrDefault(emptyList())
val previous = (devices.selectedItem as? AdbDevice)?.serial ?: settings.snapshot().device
if ((0 until devices.itemCount).map { devices.getItemAt(it) } != found) {
updatingDevices = true
try {
devices.model = DefaultComboBoxModel(found.toTypedArray())
devices.selectedItem = AdbDevices.choose(found, previous)
} finally { updatingDevices = false }
}
deviceStatus.text = result.exceptionOrNull()?.message ?: if (found.isEmpty()) "没有检测到设备;请连接手机或启动模拟器" else "${found.count { it.online }} 台可用设备;可自动识别插拔"
}
} finally { refreshing.set(false) }
}
}
}
private fun append(text: String) = ApplicationManager.getApplication().invokeLater {
if (!disposed && !project.isDisposed) { log.append(text + "\n"); log.caretPosition = log.document.length }
}
private fun hash(data: ByteArray) = MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) }
private fun request(base: String, secret: String, method: String, route: String, body: Any? = null): ByteArray {
val publisher = if (body == null) HttpRequest.BodyPublishers.noBody() else HttpRequest.BodyPublishers.ofString(gson.toJson(body))
val req = HttpRequest.newBuilder(URI.create(base + "/api/v1" + route)).timeout(Duration.ofMinutes(5))
.header("Authorization", "Bearer $secret").header("Content-Type", "application/json").method(method, publisher).build()
val response = http.send(req, HttpResponse.BodyHandlers.ofByteArray())
check(response.statusCode() in 200..299) { "HTTP ${response.statusCode()}: ${String(response.body()).take(500)}" }
return response.body()
}
private fun json(base: String, secret: String, method: String, route: String, body: Any? = null) =
gson.fromJson(String(request(base, secret, method, route, body)), JsonObject::class.java)
fun runBuild() {
if (busy) return
busy = true; run.isEnabled = false
// ToolWindow.show callbacks in newer IDEs can run on Dispatchers.UI(RELAX).
// Application.invokeLater supplies write intent across supported IDE versions.
// Do not link WriteIntentReadAction.run: its binary signature changed in newer IDEs.
ApplicationManager.getApplication().invokeLater {
if (disposed || project.isDisposed) { busy = false; return@invokeLater }
try {
FileDocumentManager.getInstance().saveAllDocuments()
beginBuild()
} catch (e: Exception) {
busy = false; run.isEnabled = true; append("无法启动:${e.message ?: e.javaClass.simpleName}")
}
}
}
private fun beginBuild() {
val cfg = settings.snapshot()
val base = cfg.url.trim().trimEnd('/')
validateEndpoint(base)
val selected = devices.selectedItem as? AdbDevice
if (cfg.install) {
require(selected == null || selected.online) { "请选择已连接且已授权的设备" }
if (selected != null) cfg.device = selected.serial
}
val source = project.basePath?.let { Path.of(it) } ?: error("项目路径不存在")
cancelRequested = false; activeBuild = ""; log.text = ""
object : Task.Backgroundable(project, "Remote Compilation", false) {
override fun run(indicator: ProgressIndicator) {
var secret = ""
try {
secret = PasswordSafe.instance.getPassword(credentials(base)) ?: ""
check(secret.length >= 24) { "请在右侧 Remote Configuration 中保存服务 Token" }
if (cfg.install) {
val connected = AdbDevices.list(AdbDevices.resolve(source, cfg.adb)).filter { it.online }
val target = AdbDevices.choose(connected, selected?.serial ?: cfg.device, explicit = selected != null)
check(target != null) { "请从设备列表选择已连接且已授权的设备" }
cfg.device = target.serial
settings.selectDevice(target.serial)
refreshDevices()
append("目标设备:$target")
}
json(base, secret, "GET", "/health")
if (cfg.projectId.isBlank()) {
cfg.projectId = json(base, secret, "POST", "/projects").get("id").asString
settings.projectAllocated(base, cfg.projectId)
}
val manifest = json(base, secret, "GET", "/projects/${cfg.projectId}/manifest").getAsJsonObject("files")
val files = linkedMapOf<String, Map<String, String>>()
val excludes = setOf(".git", ".gradle", ".idea", "build", ".remotecompile", "node_modules", ".kotlin")
var changed = 0
Files.walk(source).use { paths -> paths.filter { path ->
val rel = source.relativize(path)
rel.none { it.toString() in excludes } && !Files.isDirectory(path)
}.forEach { path ->
check(!Files.isSymbolicLink(path)) { "暂不支持符号链接:$path" }
val name = source.relativize(path).joinToString("/")
val leaf = path.fileName.toString()
if (leaf == "local.properties" || leaf.endsWith(".jks") || leaf.endsWith(".keystore") || leaf.startsWith(".env") || leaf in setOf("key.properties", "keystore.properties")) return@forEach
check(Files.size(path) <= 64L * 1024 * 1024) { "文件超过首版 64MiB 上限:$name" }
val bytes = Files.readAllBytes(path); val hash = hash(bytes)
files[name] = if (manifest?.getAsJsonObject(name)?.get("hash")?.asString == hash) mapOf("hash" to hash)
else { changed++; mapOf("hash" to hash, "data" to Base64.getEncoder().encodeToString(bytes)) }
} }
check(!cancelRequested) { "已取消" }
val revision = UUID.randomUUID().toString()
append("同步 ${files.size} 个文件,上传 $changed 个变更文件…")
json(base, secret, "POST", "/projects/${cfg.projectId}/sync", mapOf("revision" to revision, "files" to files))
check(!cancelRequested) { "已取消" }
activeBuild = json(base, secret, "POST", "/projects/${cfg.projectId}/builds", mapOf("revision" to revision, "task" to cfg.task)).get("id").asString
var offset = 0
var result: JsonObject
while (true) {
if (cancelRequested) { json(base, secret, "DELETE", "/builds/$activeBuild"); error("已请求取消远程构建") }
result = json(base, secret, "GET", "/builds/$activeBuild")
val lines = result.getAsJsonArray("logs")
while (offset < lines.size()) append(lines[offset++].asString)
if (result.get("status").asString !in listOf("queued", "running")) break
Thread.sleep(700)
}
check(result.get("status").asString == "success") { "构建状态:${result.get("status").asString}" }
val artifacts = result.getAsJsonArray("artifacts")
check(artifacts.size() == 1) { "首版要求恰好一个 APK,实际 ${artifacts.size()} 个;请调整构建任务" }
val artifact = artifacts[0].asJsonObject
val name = artifact.get("name").asString
val encodedName = URLEncoder.encode(name, Charsets.UTF_8).replace("+", "%20")
val bytes = request(base, secret, "GET", "/builds/$activeBuild/artifacts/$encodedName")
check(hash(bytes) == artifact.get("hash").asString) { "APK 校验失败" }
val output = source.resolve(".remotecompile").resolve("$activeBuild.apk")
Files.createDirectories(output.parent); Files.write(output, bytes)
append("APK 已保存:$output")
check(!cancelRequested) { "已取消安装" }
if (cfg.install) {
val adb = AdbDevices.resolve(source, cfg.adb)
check(AdbDevices.list(adb).any { it.serial == cfg.device && it.online }) { "目标设备已断开或未授权,已保留 APK" }
val pb = ProcessBuilder(adb, "-s", cfg.device, "install", "-r", output.toString()).redirectErrorStream(true)
val outputLog = Files.createTempFile("remotecompile-adb-", ".log")
try {
val process = pb.redirectOutput(outputLog.toFile()).start()
if (!process.waitFor(120, TimeUnit.SECONDS)) { process.destroyForcibly(); error("adb 安装超时") }
append(Files.readString(outputLog)); check(process.exitValue() == 0) { "adb 安装失败" }
} finally { Files.deleteIfExists(outputLog) }
}
append("Remote Run 完成")
} catch (e: Exception) {
// Never print request headers or the token.
append("失败:" + (e.message ?: e.javaClass.simpleName).let { if (secret.isNotEmpty()) it.replace(secret, "***") else it })
} finally {
activeBuild = ""; busy = false
ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true }
}
}
}.queue()
}
}
@@ -0,0 +1,100 @@
package studio.tongtong.remotecompile
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.components.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.ui.content.ContentFactory
import java.awt.BorderLayout
import java.awt.GridLayout
import java.net.URI
import javax.swing.*
@State(name = "RemoteCompilation", storages = [Storage("remote-compilation.xml")])
@Service(Service.Level.PROJECT)
class Settings : PersistentStateComponent<Settings.Data> {
data class Data(
var url: String = "http://127.0.0.1:8765",
var projectId: String = "",
var task: String = ":app:assembleDebug",
var adb: String = "",
var device: String = "",
var install: Boolean = false
)
@Volatile private var data = Data()
@Synchronized fun snapshot(): Data = data.copy()
override fun getState(): Data = snapshot()
@Synchronized override fun loadState(state: Data) { data = state.copy() }
@Synchronized fun saveConfiguration(next: Data) {
data = next.copy(projectId = if (data.url == next.url) data.projectId else "", device = data.device)
}
@Synchronized fun selectDevice(serial: String) { data = data.copy(device = serial) }
@Synchronized fun projectAllocated(url: String, id: String) {
if (data.url == url) data = data.copy(projectId = id)
}
}
internal fun credentials(endpoint: String) = CredentialAttributes("RemoteCompilation:$endpoint")
internal fun validateEndpoint(base: String) {
val uri = runCatching { URI.create(base) }.getOrNull()
require(uri != null && uri.host != null && uri.scheme in listOf("http", "https") &&
uri.rawUserInfo == null && uri.rawQuery == null && uri.rawFragment == null) { "服务地址无效" }
require(uri.scheme != "http" || uri.host in listOf("localhost", "127.0.0.1", "[::1]")) {
"远程连接请使用 HTTPS 或 SSH 隧道到本机端口"
}
}
class RemoteSettingsToolWindow : ToolWindowFactory {
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
toolWindow.contentManager.addContent(ContentFactory.getInstance().createContent(RemoteSettingsPanel(project), "连接设置", false))
}
}
private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderLayout()) {
private val settings = project.getService(Settings::class.java)
private val original = settings.snapshot()
private val url = JTextField(original.url)
private val token = JPasswordField()
private val task = JTextField(original.task)
private val adb = JTextField(original.adb)
private val install = JCheckBox("构建成功后安装到所选设备", original.install)
private val save = JButton("保存配置")
private val status = JLabel("Token 留空保留已保存值")
init {
val fields = JPanel(GridLayout(0, 1, 0, 5))
listOf("服务地址" to url, "Token(留空保留)" to token, "Gradle 任务" to task,
"adb 路径(留空自动使用项目 SDK)" to adb).forEach { (label, field) -> fields.add(JLabel(label)); fields.add(field) }
fields.add(install); fields.add(save); fields.add(status)
border = BorderFactory.createEmptyBorder(12, 12, 12, 12)
add(fields, BorderLayout.NORTH)
save.addActionListener {
val base = url.text.trim().trimEnd('/')
try { validateEndpoint(base); require(task.text.isNotBlank()) { "请填写 Gradle 任务" } }
catch (e: IllegalArgumentException) { status.text = e.message; return@addActionListener }
val entered = String(token.password); token.text = ""
val previous = settings.snapshot()
val next = previous.copy(url = base, task = task.text.trim(), adb = adb.text.trim(), install = install.isSelected,
projectId = if (previous.url == base) previous.projectId else "")
save.isEnabled = false; status.text = "正在保存…"
ApplicationManager.getApplication().executeOnPooledThread {
val failure = runCatching {
if (entered.isNotEmpty()) {
require(entered.length >= 24) { "Token 至少需要 24 个字符" }
PasswordSafe.instance.setPassword(credentials(base), entered)
}
settings.saveConfiguration(next)
}.exceptionOrNull()
ApplicationManager.getApplication().invokeLater {
if (!project.isDisposed) {
save.isEnabled = true
status.text = if (failure == null) "已保存;点击工具栏 Remote Run 执行" else "保存失败,请检查 Token 或密码库"
project.getService(PanelService::class.java).panel?.refreshDevices()
}
}
}
}
}
}