leejunyoung5819wayland-android-remote

공개

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

208줄8.0 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 var port = 27200
35
36 override fun onCreate(savedInstanceState: Bundle?) {
37 super.onCreate(savedInstanceState)
38 setContentView(buildLayout())
39 client = DaemonClient(this, onMessage = ::onMessage, onConnected = ::onConnected)
40 }
41
42 override fun onStart() {
43 super.onStart()
44 refreshAddress()
45 client.start()
46 }
47
48 override fun onStop() {
49 client.stop()
50 super.onStop()
51 }
52
53 private fun onConnected(connected: Boolean) {
54 statusView.text = if (connected) "서비스 실행 중" else "서비스 꺼짐"
55 statusView.setTextColor(if (connected) ACCENT else WARN)
56 if (!connected) {
57 codeView.text = "-"
58 sessionsBox.removeAllViews()
59 whitelistBox.removeAllViews()
60 whitelistBox.addView(hint("서비스가 실행 중일 때 표시됩니다"))
61 }
62 }
63
64 private fun onMessage(msg: JSONObject) {
65 if (msg.optString("type") != "state") return
66 port = msg.optInt("port", port)
67 refreshAddress()
68 val code = msg.optString("confirm")
69 codeView.text = if (code.length == 6) "${code.substring(0, 3)} ${code.substring(3)}" else code
70
71 sessionsBox.removeAllViews()
72 val sessions = msg.optJSONArray("sessions")
73 if (sessions == null || sessions.length() == 0) {
74 sessionsBox.addView(hint("연결된 PC 없음"))
75 } else {
76 for (i in 0 until sessions.length()) {
77 val s = sessions.getJSONObject(i)
78 sessionsBox.addView(row(s.optString("host"), s.optString("ip"), null))
79 }
80 }
81
82 whitelistBox.removeAllViews()
83 val list = msg.optJSONArray("whitelist")
84 if (list == null || list.length() == 0) {
85 whitelistBox.addView(hint("허용된 PC 없음"))
86 } else {
87 for (i in 0 until list.length()) {
88 val e = list.getJSONObject(i)
89 val key = e.optString("key")
90 val host = e.optString("host").ifEmpty { "이름 없음" }
91 whitelistBox.addView(row(host, "키 ${key.take(16)}…") { confirmRevoke(host, key) })
92 }
93 }
94 }
95
96 private fun confirmRevoke(host: String, key: String) {
97 AlertDialog.Builder(this)
98 .setTitle("$host 삭제")
99 .setMessage("이 PC의 허용을 철회합니다. 연결 중이면 바로 끊기고, 다시 연결하려면 승인이 필요합니다.")
100 .setPositiveButton("삭제") { _, _ -> client.send(JSONObject().put("type", "revoke").put("key", key)) }
101 .setNegativeButton("취소", null)
102 .show()
103 }
104
105 /** 현재 네트워크의 IPv4 주소. 호스트 IP 입력창에 넣을 값이다. */
106 private fun refreshAddress() {
107 val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
108 val props: LinkProperties? = cm.getLinkProperties(cm.activeNetwork)
109 val ip = props?.linkAddresses?.map { it.address }?.firstOrNull { it is Inet4Address }?.hostAddress
110 addressView.text = when {
111 ip == null -> "네트워크 연결 없음"
112 port == 27200 -> ip
113 else -> "$ip:$port"
114 }
115 }
116
117 private fun buildLayout(): View {
118 val pad = dp(20)
119 val root = LinearLayout(this).apply {
120 orientation = LinearLayout.VERTICAL
121 setPadding(pad, dp(32), pad, pad)
122 setBackgroundColor(BG)
123 }
124 root.addView(label("Android Remote", 24f, bold = true))
125 statusView = label("확인 중…", 15f, color = Color.LTGRAY).apply { setPadding(0, dp(4), 0, dp(16)) }
126 root.addView(statusView)
127
128 val card = card()
129 card.addView(label("PC에서 입력할 주소", 13f, color = Color.GRAY))
130 addressView = label("-", 26f, bold = true).apply { typeface = Typeface.MONOSPACE }
131 card.addView(addressView)
132 card.addView(label("확인 코드", 13f, color = Color.GRAY).apply { setPadding(0, dp(12), 0, 0) })
133 codeView = label("-", 20f, bold = true).apply { typeface = Typeface.MONOSPACE }
134 card.addView(codeView)
135 root.addView(card)
136
137 root.addView(section("연결 중인 PC"))
138 sessionsBox = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
139 root.addView(sessionsBox)
140
141 root.addView(section("허용된 PC"))
142 whitelistBox = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
143 root.addView(whitelistBox)
144
145 return ScrollView(this).apply {
146 setBackgroundColor(BG)
147 // Android 15는 화면 끝까지 그리므로 상태 표시줄·내비게이션 바 영역만큼 띄운다.
148 fitsSystemWindows = true
149 addView(root)
150 }
151 }
152
153 private fun row(title: String, subtitle: String, onDelete: (() -> Unit)?): View {
154 val row = LinearLayout(this).apply {
155 orientation = LinearLayout.HORIZONTAL
156 gravity = Gravity.CENTER_VERTICAL
157 setPadding(dp(16), dp(10), dp(8), dp(10))
158 background = rounded(CARD)
159 }
160 val texts = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
161 texts.addView(label(title, 16f))
162 texts.addView(label(subtitle, 12f, color = Color.GRAY))
163 row.addView(texts, LinearLayout.LayoutParams(0, WRAP_CONTENT, 1f))
164 if (onDelete != null) {
165 row.addView(Button(this).apply {
166 text = "삭제"
167 setOnClickListener { onDelete() }
168 })
169 }
170 return row.also {
171 it.layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply { bottomMargin = dp(8) }
172 }
173 }
174
175 private fun card() = LinearLayout(this).apply {
176 orientation = LinearLayout.VERTICAL
177 setPadding(dp(16), dp(16), dp(16), dp(16))
178 background = rounded(CARD)
179 }
180
181 private fun section(text: String) = label(text, 14f, bold = true, color = Color.LTGRAY).apply {
182 setPadding(0, dp(24), 0, dp(8))
183 }
184
185 private fun hint(text: String) = label(text, 14f, color = Color.GRAY).apply { setPadding(dp(4), dp(4), 0, dp(4)) }
186
187 private fun label(text: String, size: Float, bold: Boolean = false, color: Int = Color.WHITE) =
188 TextView(this).apply {
189 this.text = text
190 textSize = size
191 setTextColor(color)
192 if (bold) typeface = Typeface.DEFAULT_BOLD
193 }
194
195 private fun rounded(color: Int) = GradientDrawable().apply {
196 setColor(color)
197 cornerRadius = dp(14).toFloat()
198 }
199
200 private fun dp(v: Int) = (v * resources.displayMetrics.density).toInt()
201
202 companion object {
203 private val BG = Color.rgb(0x10, 0x10, 0x10)
204 private val CARD = Color.rgb(0x1e, 0x1e, 0x1e)
205 private val ACCENT = Color.rgb(0x5c, 0xc8, 0x8a)
206 private val WARN = Color.rgb(0xe0, 0x8a, 0x5c)
207 }
208}