leejunyoung5819wayland-android-remote

공개

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

346줄14 KB
1package com.androidremote.daemon
2
3import android.os.SystemClock
4import android.view.InputDevice
5import android.view.KeyCharacterMap
6import android.view.KeyEvent
7import android.view.MotionEvent
8
9/**
10 * 호스트 입력을 Android 입력 이벤트로 바꿔 주입한다 (기획서 7.3 4~5항, 3.1).
11 * 세션마다 하나씩 두고 제어 연결 스레드에서만 호출한다.
12 */
13class InputInjector {
14 private class Pointer(val id: Int, var x: Float, var y: Float, var pressure: Float)
15
16 private val pointers = ArrayList<Pointer>()
17 private var touchDownTime = 0L
18 private val keyDownTimes = HashMap<Int, Long>()
19 private var displayCache: Pair<Int, Int>? = null
20 private var displayCachedAt = 0L
21
22 /** 현재 디스플레이 크기. 회전에 따라 바뀌므로 0.5초마다 다시 읽는다. */
23 private fun display(): Pair<Int, Int> {
24 val now = SystemClock.uptimeMillis()
25 if (displayCache == null || now - displayCachedAt > 500) {
26 displayCache = SystemAccess.displaySize() ?: displayCache ?: (1080 to 2400)
27 displayCachedAt = now
28 }
29 return displayCache!!
30 }
31
32 /** 영상 프레임 좌표를 실제 디스플레이 좌표로 바꾼다. */
33 private fun toDisplay(x: Int, y: Int, fw: Int, fh: Int): Pair<Float, Float> {
34 val (dw, dh) = display()
35 return (x + 0.5f) * dw / fw to (y + 0.5f) * dh / fh
36 }
37
38 /**
39 * 오른쪽 버튼 길게 누르기 (기획서 7.3 4항). 시작 시각과, 너무 일찍 뗐을 때 미뤄 둔 UP.
40 * 세게 누르기(DEEP_PRESS)를 모르는 앱도 길게 누르기로 판정하도록 UP을 길게 누르기 시간 뒤로 미룬다.
41 */
42 private var longPressAt = 0L
43 private var deferredUp: Messages.TouchEvent? = null
44 private val lock = Any()
45
46 fun touch(t: Messages.TouchEvent) = synchronized(lock) {
47 // 미뤄 둔 UP이 있으면 다음 터치보다 먼저 보낸다.
48 deferredUp?.let { deferredUp = null; finishUp(it) }
49 if (t.action == TouchAction.UP && longPressAt != 0L && pointers.size == 1 && pointers[0].id == t.pointerId) {
50 val wait = longPressAt + LongPress.holdMs() - SystemClock.uptimeMillis()
51 if (wait > 0) {
52 // 너무 일찍 떼면 길게 누르기로 판정되기 전에 끝나므로 UP을 미룬다.
53 deferredUp = t
54 scheduler.schedule({
55 synchronized(lock) { if (deferredUp === t) { deferredUp = null; finishUp(t) } }
56 }, wait, java.util.concurrent.TimeUnit.MILLISECONDS)
57 } else {
58 finishUp(t)
59 }
60 return@synchronized
61 }
62 if (t.action == TouchAction.DOWN && t.longPress && pointers.isEmpty()) {
63 // 시스템 길게 누르기 시간을 잠깐 줄여 바로 길게 누르기가 되게 한다. 앱은 DOWN을 받을 때
64 // 이 값을 읽으므로 DOWN보다 먼저 바꾼다.
65 LongPress.shorten()
66 touchNow(t)
67 longPressAt = touchDownTime
68 // 세게 누르기(DEEP_PRESS)를 아는 View는 시간과 상관없이 바로 길게 누르기를 한다.
69 injectMotion(MotionEvent.ACTION_MOVE, SystemClock.uptimeMillis(), LongPress.CLASSIFICATION_DEEP_PRESS)
70 return@synchronized
71 }
72 touchNow(t)
73 if (pointers.isEmpty()) endLongPress()
74 }
75
76 private fun finishUp(t: Messages.TouchEvent) {
77 touchNow(t)
78 if (pointers.isEmpty()) endLongPress()
79 }
80
81 private fun endLongPress() {
82 if (longPressAt != 0L) {
83 longPressAt = 0L
84 LongPress.restore()
85 }
86 }
87
88 private fun touchNow(t: Messages.TouchEvent) {
89 val (x, y) = toDisplay(t.x, t.y, t.frameWidth, t.frameHeight)
90 val now = SystemClock.uptimeMillis()
91 val pressure = t.pressure / 65535f
92 val action: Int
93 when (t.action) {
94 TouchAction.DOWN -> {
95 if (pointers.any { it.id == t.pointerId }) return
96 if (pointers.isEmpty()) touchDownTime = now
97 pointers.add(Pointer(t.pointerId, x, y, pressure))
98 val index = pointers.size - 1
99 action = if (index == 0) MotionEvent.ACTION_DOWN
100 else MotionEvent.ACTION_POINTER_DOWN or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
101 }
102 TouchAction.MOVE -> {
103 val p = pointers.firstOrNull { it.id == t.pointerId } ?: return
104 p.x = x; p.y = y; p.pressure = pressure
105 action = MotionEvent.ACTION_MOVE
106 }
107 TouchAction.UP -> {
108 val index = pointers.indexOfFirst { it.id == t.pointerId }
109 if (index < 0) return
110 pointers[index].x = x
111 pointers[index].y = y
112 action = if (pointers.size == 1) MotionEvent.ACTION_UP
113 else MotionEvent.ACTION_POINTER_UP or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
114 }
115 TouchAction.CANCEL -> {
116 if (pointers.isEmpty()) return
117 action = MotionEvent.ACTION_CANCEL
118 }
119 else -> return
120 }
121 injectMotion(action, now)
122 when (t.action) {
123 TouchAction.UP -> pointers.removeAll { it.id == t.pointerId }
124 TouchAction.CANCEL -> pointers.clear()
125 }
126 }
127
128 /** 연결이 끊길 때 눌린 채로 남은 터치를 정리한다. */
129 fun releaseAll() = synchronized(lock) {
130 deferredUp = null
131 endLongPress()
132 if (pointers.isNotEmpty()) {
133 injectMotion(MotionEvent.ACTION_CANCEL, SystemClock.uptimeMillis())
134 pointers.clear()
135 }
136 for (keycode in keyDownTimes.keys.toList()) key(KeyAction.UP, keycode, 0, 0, 0)
137 }
138
139 private fun injectMotion(action: Int, now: Long, classification: Int = 0) {
140 val props = Array(pointers.size) { i ->
141 MotionEvent.PointerProperties().apply {
142 id = pointers[i].id
143 toolType = MotionEvent.TOOL_TYPE_FINGER
144 }
145 }
146 val coords = Array(pointers.size) { i ->
147 MotionEvent.PointerCoords().apply {
148 x = pointers[i].x
149 y = pointers[i].y
150 pressure = if (action == MotionEvent.ACTION_UP) 0f else pointers[i].pressure
151 size = 1f
152 }
153 }
154 val e = LongPress.obtainClassified(touchDownTime, now, action, props, coords, classification)
155 ?: MotionEvent.obtain(
156 touchDownTime, now, action, pointers.size, props, coords,
157 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0,
158 )
159 SystemAccess.injectEvent(e)
160 e.recycle()
161 }
162
163 companion object {
164 /** 미룬 UP을 보내는 타이머. 데몬 전체에서 하나만 쓴다. */
165 private val scheduler = java.util.concurrent.Executors.newSingleThreadScheduledExecutor { r ->
166 Thread(r, "deferred-touch").apply { isDaemon = true }
167 }
168 }
169
170 fun scroll(s: Messages.ScrollEvent) {
171 val (x, y) = toDisplay(s.x, s.y, s.frameWidth, s.frameHeight)
172 val now = SystemClock.uptimeMillis()
173 val props = arrayOf(MotionEvent.PointerProperties().apply {
174 id = 0
175 toolType = MotionEvent.TOOL_TYPE_MOUSE
176 })
177 val coords = arrayOf(MotionEvent.PointerCoords().apply {
178 this.x = x
179 this.y = y
180 setAxisValue(MotionEvent.AXIS_VSCROLL, s.vScroll / 120f)
181 setAxisValue(MotionEvent.AXIS_HSCROLL, s.hScroll / 120f)
182 })
183 val e = MotionEvent.obtain(
184 now, now, MotionEvent.ACTION_SCROLL, 1, props, coords,
185 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_MOUSE, 0,
186 )
187 SystemAccess.injectEvent(e)
188 e.recycle()
189 }
190
191 fun key(action: Int, keycode: Int, meta: Int, repeat: Int, scancode: Int) {
192 val now = SystemClock.uptimeMillis()
193 fun inject(a: Int, down: Long) = SystemAccess.injectEvent(
194 KeyEvent(down, now, a, keycode, repeat, meta, KeyCharacterMap.VIRTUAL_KEYBOARD,
195 scancode, 0, InputDevice.SOURCE_KEYBOARD),
196 )
197 when (action) {
198 KeyAction.DOWN -> {
199 val down = if (repeat > 0) keyDownTimes[keycode] ?: now else now
200 keyDownTimes[keycode] = down
201 inject(KeyEvent.ACTION_DOWN, down)
202 }
203 KeyAction.UP -> inject(KeyEvent.ACTION_UP, keyDownTimes.remove(keycode) ?: now)
204 KeyAction.CLICK -> {
205 inject(KeyEvent.ACTION_DOWN, now)
206 inject(KeyEvent.ACTION_UP, now)
207 }
208 }
209 }
210
211 /**
212 * 문자열을 입력한다. 가상 키보드 키맵으로 만들 수 있는 문자(ASCII 등)는 키 이벤트로 넣고,
213 * 한글처럼 키 이벤트로 만들 수 없는 문자는 클립보드에 넣고 붙여넣는다.
214 */
215 fun text(text: String) {
216 val events = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD).getEvents(text.toCharArray())
217 if (events != null) {
218 for (e in events) SystemAccess.injectEvent(e)
219 return
220 }
221 // 입력용으로 넣은 텍스트가 클립보드 동기화로 호스트에 되돌아가지 않게 표시한다.
222 ClipboardSync.markOwn(text)
223 if (ClipboardAccess.setText(text)) {
224 SystemAccess.paste()
225 } else {
226 Log.w("텍스트 입력 실패: 클립보드 설정 불가")
227 }
228 }
229
230 object TouchAction {
231 const val DOWN = 0
232 const val UP = 1
233 const val MOVE = 2
234 const val CANCEL = 3
235 }
236
237 object KeyAction {
238 const val DOWN = 0
239 const val UP = 1
240 const val CLICK = 2
241 }
242}
243
244/**
245 * 즉시 길게 누르기. MotionEvent에 세게 누르기(CLASSIFICATION_DEEP_PRESS, Android 10+) 분류를 달려면
246 * 숨은 `MotionEvent.obtain(..., displayId, flags, classification)`을 써야 한다. 없으면 null을 돌려주고
247 * 호출 측은 분류 없는 이벤트를 쓴다(그래도 UP을 미뤄 길게 누르기는 된다).
248 */
249object LongPress {
250 const val CLASSIFICATION_DEEP_PRESS = 2
251 /** 오른쪽 클릭 동안 쓰는 길게 누르기 시간. */
252 private const val SHORT_MS = 120L
253 private const val KEY = "long_press_timeout"
254
255 /** 원래 값을 적어 두는 파일. 줄인 채로 데몬이 죽어도 다음 시작 때 되돌린다. */
256 private var marker: java.io.File? = null
257 /** 줄이기 전 값. 설정에 없었으면 "null". 줄여 둔 동안만 null이 아니다. */
258 private var original: String? = null
259
260 /** 데몬 시작 시 호출. 지난번에 줄인 채로 끝났으면 원래 값으로 되돌린다. */
261 fun recover(dataDir: java.io.File) {
262 val f = java.io.File(dataDir, "long_press_timeout.orig")
263 marker = f
264 if (f.exists()) {
265 val v = f.readText().trim()
266 Log.i("길게 누르기 시간 복원: $v")
267 put(v)
268 f.delete()
269 }
270 }
271
272 /** 원래 길게 누르기 시간 + 여유. 줄여 둔 동안은 짧은 값 기준. */
273 fun holdMs(): Long =
274 (if (original != null) SHORT_MS else (original ?: current()).toLongOrNull() ?: 500L) + 80
275
276 @Synchronized
277 fun shorten() {
278 if (original != null) return
279 val cur = current()
280 runCatching { marker?.writeText(cur) }
281 original = cur
282 put(SHORT_MS.toString())
283 // 바뀐 값이 앱 프로세스에 전달될 시간을 준다.
284 Thread.sleep(40)
285 }
286
287 @Synchronized
288 fun restore() {
289 val v = original ?: return
290 original = null
291 put(v)
292 runCatching { marker?.delete() }
293 }
294
295 private fun current(): String = cmd("get", KEY).ifEmpty { "null" }
296
297 private fun put(value: String) {
298 if (value == "null") cmd("delete", KEY) else cmd("put", KEY, value)
299 }
300
301 /** `cmd settings`는 앱 프로세스를 띄우지 않아 `settings`보다 빠르다 (약 25ms). */
302 private fun cmd(vararg args: String): String = try {
303 val p = Runtime.getRuntime().exec(arrayOf("cmd", "settings", args[0], "secure", *args.drop(1).toTypedArray()))
304 val out = p.inputStream.bufferedReader().readText().trim()
305 p.waitFor()
306 out
307 } catch (e: Exception) {
308 Log.w("설정 명령 실패 (${args.joinToString(" ")}): $e")
309 ""
310 }
311
312 private val obtain: java.lang.reflect.Method? by lazy {
313 try {
314 MotionEvent::class.java.getMethod(
315 "obtain",
316 Long::class.javaPrimitiveType, Long::class.javaPrimitiveType, Int::class.javaPrimitiveType,
317 Int::class.javaPrimitiveType, Array<MotionEvent.PointerProperties>::class.java,
318 Array<MotionEvent.PointerCoords>::class.java, Int::class.javaPrimitiveType,
319 Int::class.javaPrimitiveType, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType,
320 Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, Int::class.javaPrimitiveType,
321 Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, Int::class.javaPrimitiveType,
322 )
323 } catch (e: Exception) {
324 Log.w("분류 지정 MotionEvent.obtain 없음, 즉시 길게 누르기는 시간 대기로 대신함: $e")
325 null
326 }
327 }
328
329 fun obtainClassified(
330 downTime: Long, eventTime: Long, action: Int,
331 props: Array<MotionEvent.PointerProperties>, coords: Array<MotionEvent.PointerCoords>,
332 classification: Int,
333 ): MotionEvent? {
334 if (classification == 0) return null
335 val m = obtain ?: return null
336 return try {
337 m.invoke(
338 null, downTime, eventTime, action, props.size, props, coords,
339 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0, 0, classification,
340 ) as MotionEvent
341 } catch (e: Exception) {
342 Log.w("분류 지정 MotionEvent 생성 실패: ${e.cause ?: e}")
343 null
344 }
345 }
346}