leejunyoung5819wayland-android-remote

공개

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

280줄11 KB
1package com.androidremote.companion
2
3import android.app.Activity
4import android.app.AlertDialog
5import android.content.Context
6import android.graphics.Color
7import android.graphics.Typeface
8import android.graphics.drawable.GradientDrawable
9import android.net.ConnectivityManager
10import android.net.LinkProperties
11import android.os.Bundle
12import android.view.Gravity
13import android.view.View
14import android.view.ViewGroup.LayoutParams.MATCH_PARENT
15import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
16import android.widget.Button
17import android.widget.LinearLayout
18import android.widget.ScrollView
19import android.widget.TextView
20import org.json.JSONObject
21import java.net.Inet4Address
22
23/**
24 * 동반 앱 메인 화면 (기획서 5.1, 5.2). 데몬 상태, 이 기기의 내부망 IP, 확인 코드,
25 * 연결 중인 PC, 허용된 PC 목록과 삭제(권한 철회)를 보여준다.
26 */
27class MainActivity : Activity() {
28 private lateinit var client: DaemonClient
29 private lateinit var statusView: TextView
30 private lateinit var addressView: TextView
31 private lateinit var codeView: TextView
32 private lateinit var sessionsBox: LinearLayout
33 private lateinit var whitelistBox: LinearLayout
34 private lateinit var startCard: LinearLayout
35 private lateinit var startStatus: TextView
36 private lateinit var startButton: Button
37 private var port = 27200
38
39 override fun onCreate(savedInstanceState: Bundle?) {
40 super.onCreate(savedInstanceState)
41 setContentView(buildLayout())
42 client = DaemonClient(this, onMessage = ::onMessage, onConnected = ::onConnected)
43 }
44
45 override fun onStart() {
46 super.onStart()
47 refreshAddress()
48 client.start()
49 }
50
51 override fun onStop() {
52 client.stop()
53 super.onStop()
54 }
55
56 private fun onConnected(connected: Boolean) {
57 startCard.visibility = if (connected) View.GONE else View.VISIBLE
58 refreshStartCard()
59 statusView.text = if (connected) "서비스 실행 중" else "서비스 꺼짐"
60 statusView.setTextColor(if (connected) ACCENT else WARN)
61 if (!connected) {
62 codeView.text = "-"
63 sessionsBox.removeAllViews()
64 whitelistBox.removeAllViews()
65 whitelistBox.addView(hint("서비스가 실행 중일 때 표시됩니다"))
66 }
67 }
68
69 private fun onMessage(msg: JSONObject) {
70 if (msg.optString("type") != "state") return
71 port = msg.optInt("port", port)
72 refreshAddress()
73 val code = msg.optString("confirm")
74 codeView.text = if (code.length == 6) "${code.substring(0, 3)} ${code.substring(3)}" else code
75
76 sessionsBox.removeAllViews()
77 val sessions = msg.optJSONArray("sessions")
78 if (sessions == null || sessions.length() == 0) {
79 sessionsBox.addView(hint("연결된 PC 없음"))
80 } else {
81 for (i in 0 until sessions.length()) {
82 val s = sessions.getJSONObject(i)
83 sessionsBox.addView(row(s.optString("host"), s.optString("ip"), null))
84 }
85 }
86
87 whitelistBox.removeAllViews()
88 val list = msg.optJSONArray("whitelist")
89 if (list == null || list.length() == 0) {
90 whitelistBox.addView(hint("허용된 PC 없음"))
91 } else {
92 for (i in 0 until list.length()) {
93 val e = list.getJSONObject(i)
94 val key = e.optString("key")
95 val host = e.optString("host").ifEmpty { "이름 없음" }
96 whitelistBox.addView(row(host, "키 ${key.take(16)}…") { confirmRevoke(host, key) })
97 }
98 }
99 }
100
101 private fun refreshStartCard() {
102 val paired = Bootstrap.isPaired(this)
103 val wifiDebug = Bootstrap.isWirelessDebuggingOn(this)
104 val auto = Bootstrap.canToggleWirelessDebugging(this)
105 startStatus.text = buildString {
106 append(if (paired) "페어링: 완료" else "페어링: 안 됨")
107 append("\n무선 디버깅: ").append(if (wifiDebug) "켜짐" else "꺼짐")
108 append("\n무선 디버깅 자동 켜기: ").append(if (auto) "가능 (재부팅 후 자동 시작)" else "서비스를 한 번 시작하면 가능")
109 if (!paired) append("\n\n처음 한 번: 개발자 옵션 > 무선 디버깅을 켜고 '페어링 코드로 기기 페어링'을 연 뒤, 알림에 6자리 코드를 입력하세요.")
110 }
111 startButton.isEnabled = paired
112 }
113
114 private fun openDeveloperSettings() {
115 runCatching { startActivity(android.content.Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)) }
116 }
117
118 private fun startPairing() {
119 if (checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
120 requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), REQ_NOTIFY)
121 return
122 }
123 PairingNotifier.show(this)
124 openDeveloperSettings()
125 }
126
127 override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, results: IntArray) {
128 super.onRequestPermissionsResult(requestCode, permissions, results)
129 if (requestCode == REQ_NOTIFY && results.firstOrNull() == android.content.pm.PackageManager.PERMISSION_GRANTED) {
130 startPairing()
131 }
132 }
133
134 private fun startDaemon() {
135 startButton.isEnabled = false
136 startStatus.text = "서비스 시작 중…"
137 Thread {
138 val r = Bootstrap.launchDaemon(applicationContext)
139 runOnUiThread {
140 refreshStartCard()
141 if (r.isFailure) startStatus.text = "시작 실패: ${r.exceptionOrNull()?.message}\n\n" + startStatus.text
142 }
143 }.start()
144 }
145
146 private fun confirmRevoke(host: String, key: String) {
147 AlertDialog.Builder(this)
148 .setTitle("$host 삭제")
149 .setMessage("이 PC의 허용을 철회합니다. 연결 중이면 바로 끊기고, 다시 연결하려면 승인이 필요합니다.")
150 .setPositiveButton("삭제") { _, _ -> client.send(JSONObject().put("type", "revoke").put("key", key)) }
151 .setNegativeButton("취소", null)
152 .show()
153 }
154
155 /** 현재 네트워크의 IPv4 주소. 호스트 IP 입력창에 넣을 값이다. */
156 private fun refreshAddress() {
157 val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
158 val props: LinkProperties? = cm.getLinkProperties(cm.activeNetwork)
159 val ip = props?.linkAddresses?.map { it.address }?.firstOrNull { it is Inet4Address }?.hostAddress
160 addressView.text = when {
161 ip == null -> "네트워크 연결 없음"
162 port == 27200 -> ip
163 else -> "$ip:$port"
164 }
165 }
166
167 private fun buildLayout(): View {
168 val pad = dp(20)
169 val root = LinearLayout(this).apply {
170 orientation = LinearLayout.VERTICAL
171 setPadding(pad, dp(32), pad, pad)
172 setBackgroundColor(BG)
173 }
174 root.addView(label("Android Remote", 24f, bold = true))
175 statusView = label("확인 중…", 15f, color = Color.LTGRAY).apply { setPadding(0, dp(4), 0, dp(16)) }
176 root.addView(statusView)
177
178 val card = card()
179 card.addView(label("PC에서 입력할 주소", 13f, color = Color.GRAY))
180 addressView = label("-", 26f, bold = true).apply { typeface = Typeface.MONOSPACE }
181 card.addView(addressView)
182 card.addView(label("확인 코드", 13f, color = Color.GRAY).apply { setPadding(0, dp(12), 0, 0) })
183 codeView = label("-", 20f, bold = true).apply { typeface = Typeface.MONOSPACE }
184 card.addView(codeView)
185 root.addView(card)
186
187 startCard = card().apply {
188 (layoutParams as? LinearLayout.LayoutParams)?.topMargin = dp(12)
189 }
190 startCard.addView(label("USB 없이 시작", 16f, bold = true))
191 startStatus = label("", 13f, color = Color.LTGRAY).apply { setPadding(0, dp(6), 0, dp(10)) }
192 startCard.addView(startStatus)
193 startCard.addView(Button(this).apply {
194 text = "무선 디버깅 설정 열기"
195 setOnClickListener { openDeveloperSettings() }
196 })
197 startCard.addView(Button(this).apply {
198 text = "페어링 코드 입력 (최초 1회)"
199 setOnClickListener { startPairing() }
200 })
201 startButton = Button(this).apply {
202 text = "서비스 시작"
203 setOnClickListener { startDaemon() }
204 }
205 startCard.addView(startButton)
206 root.addView(startCard, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply { topMargin = dp(12) })
207
208 root.addView(section("연결 중인 PC"))
209 sessionsBox = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
210 root.addView(sessionsBox)
211
212 root.addView(section("허용된 PC"))
213 whitelistBox = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
214 root.addView(whitelistBox)
215
216 return ScrollView(this).apply {
217 setBackgroundColor(BG)
218 // Android 15는 화면 끝까지 그리므로 상태 표시줄·내비게이션 바 영역만큼 띄운다.
219 fitsSystemWindows = true
220 addView(root)
221 }
222 }
223
224 private fun row(title: String, subtitle: String, onDelete: (() -> Unit)?): View {
225 val row = LinearLayout(this).apply {
226 orientation = LinearLayout.HORIZONTAL
227 gravity = Gravity.CENTER_VERTICAL
228 setPadding(dp(16), dp(10), dp(8), dp(10))
229 background = rounded(CARD)
230 }
231 val texts = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
232 texts.addView(label(title, 16f))
233 texts.addView(label(subtitle, 12f, color = Color.GRAY))
234 row.addView(texts, LinearLayout.LayoutParams(0, WRAP_CONTENT, 1f))
235 if (onDelete != null) {
236 row.addView(Button(this).apply {
237 text = "삭제"
238 setOnClickListener { onDelete() }
239 })
240 }
241 return row.also {
242 it.layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply { bottomMargin = dp(8) }
243 }
244 }
245
246 private fun card() = LinearLayout(this).apply {
247 orientation = LinearLayout.VERTICAL
248 setPadding(dp(16), dp(16), dp(16), dp(16))
249 background = rounded(CARD)
250 }
251
252 private fun section(text: String) = label(text, 14f, bold = true, color = Color.LTGRAY).apply {
253 setPadding(0, dp(24), 0, dp(8))
254 }
255
256 private fun hint(text: String) = label(text, 14f, color = Color.GRAY).apply { setPadding(dp(4), dp(4), 0, dp(4)) }
257
258 private fun label(text: String, size: Float, bold: Boolean = false, color: Int = Color.WHITE) =
259 TextView(this).apply {
260 this.text = text
261 textSize = size
262 setTextColor(color)
263 if (bold) typeface = Typeface.DEFAULT_BOLD
264 }
265
266 private fun rounded(color: Int) = GradientDrawable().apply {
267 setColor(color)
268 cornerRadius = dp(14).toFloat()
269 }
270
271 private fun dp(v: Int) = (v * resources.displayMetrics.density).toInt()
272
273 companion object {
274 private const val REQ_NOTIFY = 1
275 private val BG = Color.rgb(0x10, 0x10, 0x10)
276 private val CARD = Color.rgb(0x1e, 0x1e, 0x1e)
277 private val ACCENT = Color.rgb(0x5c, 0xc8, 0x8a)
278 private val WARN = Color.rgb(0xe0, 0x8a, 0x5c)
279 }
280}