leejunyoung5819wayland-android-remote

공개

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

182줄6.9 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 fun touch(t: Messages.TouchEvent) {
39 val (x, y) = toDisplay(t.x, t.y, t.frameWidth, t.frameHeight)
40 val now = SystemClock.uptimeMillis()
41 val pressure = t.pressure / 65535f
42 val action: Int
43 when (t.action) {
44 TouchAction.DOWN -> {
45 if (pointers.any { it.id == t.pointerId }) return
46 if (pointers.isEmpty()) touchDownTime = now
47 pointers.add(Pointer(t.pointerId, x, y, pressure))
48 val index = pointers.size - 1
49 action = if (index == 0) MotionEvent.ACTION_DOWN
50 else MotionEvent.ACTION_POINTER_DOWN or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
51 }
52 TouchAction.MOVE -> {
53 val p = pointers.firstOrNull { it.id == t.pointerId } ?: return
54 p.x = x; p.y = y; p.pressure = pressure
55 action = MotionEvent.ACTION_MOVE
56 }
57 TouchAction.UP -> {
58 val index = pointers.indexOfFirst { it.id == t.pointerId }
59 if (index < 0) return
60 pointers[index].x = x
61 pointers[index].y = y
62 action = if (pointers.size == 1) MotionEvent.ACTION_UP
63 else MotionEvent.ACTION_POINTER_UP or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
64 }
65 TouchAction.CANCEL -> {
66 if (pointers.isEmpty()) return
67 action = MotionEvent.ACTION_CANCEL
68 }
69 else -> return
70 }
71 injectMotion(action, now)
72 when (t.action) {
73 TouchAction.UP -> pointers.removeAll { it.id == t.pointerId }
74 TouchAction.CANCEL -> pointers.clear()
75 }
76 }
77
78 /** 연결이 끊길 때 눌린 채로 남은 터치를 정리한다. */
79 fun releaseAll() {
80 if (pointers.isNotEmpty()) {
81 injectMotion(MotionEvent.ACTION_CANCEL, SystemClock.uptimeMillis())
82 pointers.clear()
83 }
84 for (keycode in keyDownTimes.keys.toList()) key(KeyAction.UP, keycode, 0, 0, 0)
85 }
86
87 private fun injectMotion(action: Int, now: Long) {
88 val props = Array(pointers.size) { i ->
89 MotionEvent.PointerProperties().apply {
90 id = pointers[i].id
91 toolType = MotionEvent.TOOL_TYPE_FINGER
92 }
93 }
94 val coords = Array(pointers.size) { i ->
95 MotionEvent.PointerCoords().apply {
96 x = pointers[i].x
97 y = pointers[i].y
98 pressure = if (action == MotionEvent.ACTION_UP) 0f else pointers[i].pressure
99 size = 1f
100 }
101 }
102 val e = MotionEvent.obtain(
103 touchDownTime, now, action, pointers.size, props, coords,
104 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0,
105 )
106 SystemAccess.injectEvent(e)
107 e.recycle()
108 }
109
110 fun scroll(s: Messages.ScrollEvent) {
111 val (x, y) = toDisplay(s.x, s.y, s.frameWidth, s.frameHeight)
112 val now = SystemClock.uptimeMillis()
113 val props = arrayOf(MotionEvent.PointerProperties().apply {
114 id = 0
115 toolType = MotionEvent.TOOL_TYPE_MOUSE
116 })
117 val coords = arrayOf(MotionEvent.PointerCoords().apply {
118 this.x = x
119 this.y = y
120 setAxisValue(MotionEvent.AXIS_VSCROLL, s.vScroll / 120f)
121 setAxisValue(MotionEvent.AXIS_HSCROLL, s.hScroll / 120f)
122 })
123 val e = MotionEvent.obtain(
124 now, now, MotionEvent.ACTION_SCROLL, 1, props, coords,
125 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_MOUSE, 0,
126 )
127 SystemAccess.injectEvent(e)
128 e.recycle()
129 }
130
131 fun key(action: Int, keycode: Int, meta: Int, repeat: Int, scancode: Int) {
132 val now = SystemClock.uptimeMillis()
133 fun inject(a: Int, down: Long) = SystemAccess.injectEvent(
134 KeyEvent(down, now, a, keycode, repeat, meta, KeyCharacterMap.VIRTUAL_KEYBOARD,
135 scancode, 0, InputDevice.SOURCE_KEYBOARD),
136 )
137 when (action) {
138 KeyAction.DOWN -> {
139 val down = if (repeat > 0) keyDownTimes[keycode] ?: now else now
140 keyDownTimes[keycode] = down
141 inject(KeyEvent.ACTION_DOWN, down)
142 }
143 KeyAction.UP -> inject(KeyEvent.ACTION_UP, keyDownTimes.remove(keycode) ?: now)
144 KeyAction.CLICK -> {
145 inject(KeyEvent.ACTION_DOWN, now)
146 inject(KeyEvent.ACTION_UP, now)
147 }
148 }
149 }
150
151 /**
152 * 문자열을 입력한다. 가상 키보드 키맵으로 만들 수 있는 문자(ASCII 등)는 키 이벤트로 넣고,
153 * 한글처럼 키 이벤트로 만들 수 없는 문자는 클립보드에 넣고 붙여넣는다.
154 */
155 fun text(text: String) {
156 val events = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD).getEvents(text.toCharArray())
157 if (events != null) {
158 for (e in events) SystemAccess.injectEvent(e)
159 return
160 }
161 // 입력용으로 넣은 텍스트가 클립보드 동기화로 호스트에 되돌아가지 않게 표시한다.
162 ClipboardSync.markOwn(text)
163 if (ClipboardAccess.setText(text)) {
164 SystemAccess.pressKey(KeyEvent.KEYCODE_PASTE)
165 } else {
166 Log.w("텍스트 입력 실패: 클립보드 설정 불가")
167 }
168 }
169
170 object TouchAction {
171 const val DOWN = 0
172 const val UP = 1
173 const val MOVE = 2
174 const val CANCEL = 3
175 }
176
177 object KeyAction {
178 const val DOWN = 0
179 const val UP = 1
180 const val CLICK = 2
181 }
182}