leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | package com.androidremote.daemon |
| 2 | |
| 3 | import android.content.ClipData |
| 4 | import android.os.IBinder |
| 5 | import android.os.SystemClock |
| 6 | import android.view.InputDevice |
| 7 | import android.view.KeyCharacterMap |
| 8 | import android.view.KeyEvent |
| 9 | import android.view.MotionEvent |
| 10 | import java.lang.reflect.Method |
| 11 | |
| 12 | /** |
| 13 | * 호스트 입력을 Android 입력 이벤트로 바꿔 주입한다 (기획서 7.3 4~5항, 3.1). |
| 14 | * 세션마다 하나씩 두고 제어 연결 스레드에서만 호출한다. |
| 15 | */ |
| 16 | class InputInjector { |
| 17 | private class Pointer(val id: Int, var x: Float, var y: Float, var pressure: Float) |
| 18 | |
| 19 | private val pointers = ArrayList<Pointer>() |
| 20 | private var touchDownTime = 0L |
| 21 | private val keyDownTimes = HashMap<Int, Long>() |
| 22 | private var displayCache: Pair<Int, Int>? = null |
| 23 | private var displayCachedAt = 0L |
| 24 | |
| 25 | /** 현재 디스플레이 크기. 회전에 따라 바뀌므로 0.5초마다 다시 읽는다. */ |
| 26 | private fun display(): Pair<Int, Int> { |
| 27 | val now = SystemClock.uptimeMillis() |
| 28 | if (displayCache == null || now - displayCachedAt > 500) { |
| 29 | displayCache = SystemAccess.displaySize() ?: displayCache ?: (1080 to 2400) |
| 30 | displayCachedAt = now |
| 31 | } |
| 32 | return displayCache!! |
| 33 | } |
| 34 | |
| 35 | /** 영상 프레임 좌표를 실제 디스플레이 좌표로 바꾼다. */ |
| 36 | private fun toDisplay(x: Int, y: Int, fw: Int, fh: Int): Pair<Float, Float> { |
| 37 | val (dw, dh) = display() |
| 38 | return (x + 0.5f) * dw / fw to (y + 0.5f) * dh / fh |
| 39 | } |
| 40 | |
| 41 | fun touch(t: Messages.TouchEvent) { |
| 42 | val (x, y) = toDisplay(t.x, t.y, t.frameWidth, t.frameHeight) |
| 43 | val now = SystemClock.uptimeMillis() |
| 44 | val pressure = t.pressure / 65535f |
| 45 | val action: Int |
| 46 | when (t.action) { |
| 47 | TouchAction.DOWN -> { |
| 48 | if (pointers.any { it.id == t.pointerId }) return |
| 49 | if (pointers.isEmpty()) touchDownTime = now |
| 50 | pointers.add(Pointer(t.pointerId, x, y, pressure)) |
| 51 | val index = pointers.size - 1 |
| 52 | action = if (index == 0) MotionEvent.ACTION_DOWN |
| 53 | else MotionEvent.ACTION_POINTER_DOWN or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT) |
| 54 | } |
| 55 | TouchAction.MOVE -> { |
| 56 | val p = pointers.firstOrNull { it.id == t.pointerId } ?: return |
| 57 | p.x = x; p.y = y; p.pressure = pressure |
| 58 | action = MotionEvent.ACTION_MOVE |
| 59 | } |
| 60 | TouchAction.UP -> { |
| 61 | val index = pointers.indexOfFirst { it.id == t.pointerId } |
| 62 | if (index < 0) return |
| 63 | pointers[index].x = x |
| 64 | pointers[index].y = y |
| 65 | action = if (pointers.size == 1) MotionEvent.ACTION_UP |
| 66 | else MotionEvent.ACTION_POINTER_UP or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT) |
| 67 | } |
| 68 | TouchAction.CANCEL -> { |
| 69 | if (pointers.isEmpty()) return |
| 70 | action = MotionEvent.ACTION_CANCEL |
| 71 | } |
| 72 | else -> return |
| 73 | } |
| 74 | injectMotion(action, now) |
| 75 | when (t.action) { |
| 76 | TouchAction.UP -> pointers.removeAll { it.id == t.pointerId } |
| 77 | TouchAction.CANCEL -> pointers.clear() |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /** 연결이 끊길 때 눌린 채로 남은 터치를 정리한다. */ |
| 82 | fun releaseAll() { |
| 83 | if (pointers.isNotEmpty()) { |
| 84 | injectMotion(MotionEvent.ACTION_CANCEL, SystemClock.uptimeMillis()) |
| 85 | pointers.clear() |
| 86 | } |
| 87 | for (keycode in keyDownTimes.keys.toList()) key(KeyAction.UP, keycode, 0, 0, 0) |
| 88 | } |
| 89 | |
| 90 | private fun injectMotion(action: Int, now: Long) { |
| 91 | val props = Array(pointers.size) { i -> |
| 92 | MotionEvent.PointerProperties().apply { |
| 93 | id = pointers[i].id |
| 94 | toolType = MotionEvent.TOOL_TYPE_FINGER |
| 95 | } |
| 96 | } |
| 97 | val coords = Array(pointers.size) { i -> |
| 98 | MotionEvent.PointerCoords().apply { |
| 99 | x = pointers[i].x |
| 100 | y = pointers[i].y |
| 101 | pressure = if (action == MotionEvent.ACTION_UP) 0f else pointers[i].pressure |
| 102 | size = 1f |
| 103 | } |
| 104 | } |
| 105 | val e = MotionEvent.obtain( |
| 106 | touchDownTime, now, action, pointers.size, props, coords, |
| 107 | 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0, |
| 108 | ) |
| 109 | SystemAccess.injectEvent(e) |
| 110 | e.recycle() |
| 111 | } |
| 112 | |
| 113 | fun scroll(s: Messages.ScrollEvent) { |
| 114 | val (x, y) = toDisplay(s.x, s.y, s.frameWidth, s.frameHeight) |
| 115 | val now = SystemClock.uptimeMillis() |
| 116 | val props = arrayOf(MotionEvent.PointerProperties().apply { |
| 117 | id = 0 |
| 118 | toolType = MotionEvent.TOOL_TYPE_MOUSE |
| 119 | }) |
| 120 | val coords = arrayOf(MotionEvent.PointerCoords().apply { |
| 121 | this.x = x |
| 122 | this.y = y |
| 123 | setAxisValue(MotionEvent.AXIS_VSCROLL, s.vScroll / 120f) |
| 124 | setAxisValue(MotionEvent.AXIS_HSCROLL, s.hScroll / 120f) |
| 125 | }) |
| 126 | val e = MotionEvent.obtain( |
| 127 | now, now, MotionEvent.ACTION_SCROLL, 1, props, coords, |
| 128 | 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_MOUSE, 0, |
| 129 | ) |
| 130 | SystemAccess.injectEvent(e) |
| 131 | e.recycle() |
| 132 | } |
| 133 | |
| 134 | fun key(action: Int, keycode: Int, meta: Int, repeat: Int, scancode: Int) { |
| 135 | val now = SystemClock.uptimeMillis() |
| 136 | fun inject(a: Int, down: Long) = SystemAccess.injectEvent( |
| 137 | KeyEvent(down, now, a, keycode, repeat, meta, KeyCharacterMap.VIRTUAL_KEYBOARD, |
| 138 | scancode, 0, InputDevice.SOURCE_KEYBOARD), |
| 139 | ) |
| 140 | when (action) { |
| 141 | KeyAction.DOWN -> { |
| 142 | val down = if (repeat > 0) keyDownTimes[keycode] ?: now else now |
| 143 | keyDownTimes[keycode] = down |
| 144 | inject(KeyEvent.ACTION_DOWN, down) |
| 145 | } |
| 146 | KeyAction.UP -> inject(KeyEvent.ACTION_UP, keyDownTimes.remove(keycode) ?: now) |
| 147 | KeyAction.CLICK -> { |
| 148 | inject(KeyEvent.ACTION_DOWN, now) |
| 149 | inject(KeyEvent.ACTION_UP, now) |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | /** |
| 155 | * 문자열을 입력한다. 가상 키보드 키맵으로 만들 수 있는 문자(ASCII 등)는 키 이벤트로 넣고, |
| 156 | * 한글처럼 키 이벤트로 만들 수 없는 문자는 클립보드에 넣고 붙여넣는다. |
| 157 | */ |
| 158 | fun text(text: String) { |
| 159 | val events = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD).getEvents(text.toCharArray()) |
| 160 | if (events != null) { |
| 161 | for (e in events) SystemAccess.injectEvent(e) |
| 162 | return |
| 163 | } |
| 164 | // 입력용으로 넣은 텍스트가 클립보드 동기화로 호스트에 되돌아가지 않게 표시한다. |
| 165 | ClipboardSync.markOwn(text) |
| 166 | if (ClipboardAccess.setText(text)) { |
| 167 | SystemAccess.pressKey(KeyEvent.KEYCODE_PASTE) |
| 168 | } else { |
| 169 | Log.w("텍스트 입력 실패: 클립보드 설정 불가") |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | object TouchAction { |
| 174 | const val DOWN = 0 |
| 175 | const val UP = 1 |
| 176 | const val MOVE = 2 |
| 177 | const val CANCEL = 3 |
| 178 | } |
| 179 | |
| 180 | object KeyAction { |
| 181 | const val DOWN = 0 |
| 182 | const val UP = 1 |
| 183 | const val CLICK = 2 |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | /** |
| 188 | * 시스템 클립보드 접근 (shell 권한). IClipboard 메서드 시그니처가 Android 버전마다 달라 |
| 189 | * 매개변수 개수와 형식을 보고 맞는 것을 고른다. |
| 190 | */ |
| 191 | object ClipboardAccess { |
| 192 | private const val SHELL_PACKAGE = "com.android.shell" |
| 193 | |
| 194 | private val service: Any? by lazy { |
| 195 | try { |
| 196 | val sm = Class.forName("android.os.ServiceManager") |
| 197 | val binder = sm.getMethod("getService", String::class.java).invoke(null, "clipboard") as IBinder |
| 198 | val stub = Class.forName("android.content.IClipboard\$Stub") |
| 199 | stub.getMethod("asInterface", IBinder::class.java).invoke(null, binder) |
| 200 | } catch (e: Exception) { |
| 201 | Log.w("클립보드 서비스 연결 실패: $e") |
| 202 | null |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | private fun findMethod(name: String): Method? = |
| 207 | service?.javaClass?.methods?.filter { it.name == name }?.maxByOrNull { it.parameterTypes.size } |
| 208 | |
| 209 | /** (callingPackage, attributionTag?, userId, deviceId?) 순서의 나머지 인자를 형식에 맞춰 채운다. */ |
| 210 | private fun args(method: Method, first: Any?): Array<Any?> { |
| 211 | val types = method.parameterTypes |
| 212 | val out = arrayOfNulls<Any>(types.size) |
| 213 | var stringCount = 0 |
| 214 | for (i in types.indices) { |
| 215 | out[i] = when { |
| 216 | i == 0 && first != null -> first |
| 217 | types[i] == String::class.java -> if (stringCount++ == 0) SHELL_PACKAGE else null |
| 218 | types[i] == Int::class.javaPrimitiveType -> 0 |
| 219 | else -> null |
| 220 | } |
| 221 | } |
| 222 | return out |
| 223 | } |
| 224 | |
| 225 | fun setText(text: String): Boolean = try { |
| 226 | val m = findMethod("setPrimaryClip") ?: throw NoSuchMethodException("setPrimaryClip") |
| 227 | m.invoke(service, *args(m, ClipData.newPlainText("android-remote", text))) |
| 228 | true |
| 229 | } catch (e: Exception) { |
| 230 | Log.w("클립보드 설정 실패: ${e.cause ?: e}") |
| 231 | false |
| 232 | } |
| 233 | |
| 234 | /** 클립보드 변경 리스너를 등록한다. 돌려준 객체로 해제한다. */ |
| 235 | fun addListener(onChange: () -> Unit): Any? = try { |
| 236 | val listener = object : android.content.IOnPrimaryClipChangedListener.Stub() { |
| 237 | override fun dispatchPrimaryClipChanged() = onChange() |
| 238 | } |
| 239 | val m = findMethod("addPrimaryClipChangedListener") ?: throw NoSuchMethodException("addPrimaryClipChangedListener") |
| 240 | m.invoke(service, *args(m, listener)) |
| 241 | listener |
| 242 | } catch (e: Exception) { |
| 243 | Log.w("클립보드 리스너 등록 실패: ${e.cause ?: e}") |
| 244 | null |
| 245 | } |
| 246 | |
| 247 | fun removeListener(listener: Any) { |
| 248 | try { |
| 249 | val m = findMethod("removePrimaryClipChangedListener") ?: return |
| 250 | m.invoke(service, *args(m, listener)) |
| 251 | } catch (e: Exception) { |
| 252 | Log.w("클립보드 리스너 해제 실패: ${e.cause ?: e}") |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | fun getText(): String? = try { |
| 257 | val m = findMethod("getPrimaryClip") ?: throw NoSuchMethodException("getPrimaryClip") |
| 258 | val clip = m.invoke(service, *args(m, null)) as ClipData? |
| 259 | clip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text?.toString() |
| 260 | } catch (e: Exception) { |
| 261 | Log.w("클립보드 읽기 실패: ${e.cause ?: e}") |
| 262 | null |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | /** |
| 267 | * 양방향 클립보드 동기화 (기획서 3.2, 6, 7.4). 마지막으로 동기화한 텍스트의 SHA-256을 기억해 |
| 268 | * 호스트에서 받은 내용이나 입력용으로 넣은 내용이 다시 호스트로 돌아가는 무한 루프를 막는다. |
| 269 | */ |
| 270 | object ClipboardSync { |
| 271 | @Volatile private var lastHash: ByteArray? = null |
| 272 | |
| 273 | fun sha256(text: String): ByteArray = |
| 274 | java.security.MessageDigest.getInstance("SHA-256").digest(text.toByteArray(Charsets.UTF_8)) |
| 275 | |
| 276 | /** 데몬이 직접 클립보드에 넣는 텍스트. 이 내용의 변경 알림은 호스트로 보내지 않는다. */ |
| 277 | fun markOwn(text: String) { |
| 278 | lastHash = sha256(text) |
| 279 | } |
| 280 | |
| 281 | /** 호스트가 보낸 텍스트를 클립보드에 넣고, `autoPaste`면 바로 붙여넣는다. */ |
| 282 | fun fromHost(text: String, autoPaste: Boolean) { |
| 283 | markOwn(text) |
| 284 | if (ClipboardAccess.setText(text) && autoPaste) { |
| 285 | SystemAccess.pressKey(android.view.KeyEvent.KEYCODE_PASTE) |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | /** 기기 클립보드가 바뀌었을 때 호스트로 보낼 텍스트. 이미 동기화한 내용이면 null. */ |
| 290 | fun changedText(): Pair<String, ByteArray>? { |
| 291 | val text = ClipboardAccess.getText() ?: return null |
| 292 | val hash = sha256(text) |
| 293 | if (lastHash != null && java.security.MessageDigest.isEqual(hash, lastHash)) return null |
| 294 | lastHash = hash |
| 295 | return text to hash |
| 296 | } |
| 297 | } |