leejunyoung5819wayland-android-remote

공개

Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)

240줄9.1 KB
1package com.androidremote.daemon
2
3import android.content.ClipData
4import android.os.IBinder
5import android.os.SystemClock
6import android.view.InputDevice
7import android.view.KeyCharacterMap
8import android.view.KeyEvent
9import android.view.MotionEvent
10import java.lang.reflect.Method
11
12/**
13 * 호스트 입력을 Android 입력 이벤트로 바꿔 주입한다 (기획서 7.3 4~5항, 3.1).
14 * 세션마다 하나씩 두고 제어 연결 스레드에서만 호출한다.
15 */
16class 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 if (ClipboardAccess.setText(text)) {
165 SystemAccess.pressKey(KeyEvent.KEYCODE_PASTE)
166 } else {
167 Log.w("텍스트 입력 실패: 클립보드 설정 불가")
168 }
169 }
170
171 object TouchAction {
172 const val DOWN = 0
173 const val UP = 1
174 const val MOVE = 2
175 const val CANCEL = 3
176 }
177
178 object KeyAction {
179 const val DOWN = 0
180 const val UP = 1
181 const val CLICK = 2
182 }
183}
184
185/**
186 * 시스템 클립보드 접근 (shell 권한). IClipboard 메서드 시그니처가 Android 버전마다 달라
187 * 매개변수 개수와 형식을 보고 맞는 것을 고른다.
188 */
189object ClipboardAccess {
190 private const val SHELL_PACKAGE = "com.android.shell"
191
192 private val service: Any? by lazy {
193 try {
194 val sm = Class.forName("android.os.ServiceManager")
195 val binder = sm.getMethod("getService", String::class.java).invoke(null, "clipboard") as IBinder
196 val stub = Class.forName("android.content.IClipboard\$Stub")
197 stub.getMethod("asInterface", IBinder::class.java).invoke(null, binder)
198 } catch (e: Exception) {
199 Log.w("클립보드 서비스 연결 실패: $e")
200 null
201 }
202 }
203
204 private fun findMethod(name: String): Method? =
205 service?.javaClass?.methods?.filter { it.name == name }?.maxByOrNull { it.parameterTypes.size }
206
207 /** (callingPackage, attributionTag?, userId, deviceId?) 순서의 나머지 인자를 형식에 맞춰 채운다. */
208 private fun args(method: Method, first: Any?): Array<Any?> {
209 val types = method.parameterTypes
210 val out = arrayOfNulls<Any>(types.size)
211 var stringCount = 0
212 for (i in types.indices) {
213 out[i] = when {
214 i == 0 && first != null -> first
215 types[i] == String::class.java -> if (stringCount++ == 0) SHELL_PACKAGE else null
216 types[i] == Int::class.javaPrimitiveType -> 0
217 else -> null
218 }
219 }
220 return out
221 }
222
223 fun setText(text: String): Boolean = try {
224 val m = findMethod("setPrimaryClip") ?: throw NoSuchMethodException("setPrimaryClip")
225 m.invoke(service, *args(m, ClipData.newPlainText("android-remote", text)))
226 true
227 } catch (e: Exception) {
228 Log.w("클립보드 설정 실패: ${e.cause ?: e}")
229 false
230 }
231
232 fun getText(): String? = try {
233 val m = findMethod("getPrimaryClip") ?: throw NoSuchMethodException("getPrimaryClip")
234 val clip = m.invoke(service, *args(m, null)) as ClipData?
235 clip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text?.toString()
236 } catch (e: Exception) {
237 Log.w("클립보드 읽기 실패: ${e.cause ?: e}")
238 null
239 }
240}