| 1 | package io.github.leexeo.cage.mobile; |
| 2 | |
| 3 | import android.app.Activity; |
| 4 | import android.app.AlertDialog; |
| 5 | import android.app.Dialog; |
| 6 | import android.content.ClipData; |
| 7 | import android.content.ClipboardManager; |
| 8 | import android.content.Intent; |
| 9 | import android.content.SharedPreferences; |
| 10 | import android.content.res.AssetManager; |
| 11 | import android.graphics.Typeface; |
| 12 | import android.graphics.drawable.Drawable; |
| 13 | import android.graphics.drawable.GradientDrawable; |
| 14 | import android.graphics.drawable.RippleDrawable; |
| 15 | import android.content.res.ColorStateList; |
| 16 | import android.view.Gravity; |
| 17 | import android.net.Uri; |
| 18 | import android.os.Bundle; |
| 19 | import android.os.Build; |
| 20 | import android.text.InputType; |
| 21 | import android.text.Editable; |
| 22 | import android.text.TextWatcher; |
| 23 | import android.view.View; |
| 24 | import android.webkit.CookieManager; |
| 25 | import android.webkit.WebResourceRequest; |
| 26 | import android.webkit.WebResourceResponse; |
| 27 | import android.webkit.WebSettings; |
| 28 | import android.webkit.WebView; |
| 29 | import android.webkit.WebViewClient; |
| 30 | import android.widget.*; |
| 31 | import cagemobile.Cagemobile; |
| 32 | import cagemobile.Client; |
| 33 | import java.io.*; |
| 34 | import java.time.Instant; |
| 35 | import java.util.concurrent.ExecutorService; |
| 36 | import java.util.concurrent.Executors; |
| 37 | import org.json.JSONObject; |
| 38 | import org.json.JSONArray; |
| 39 | import java.util.LinkedHashMap; |
| 40 | import java.util.Map; |
| 41 | import androidx.webkit.WebViewCompat; |
| 42 | import androidx.webkit.WebViewFeature; |
| 43 | import androidx.webkit.ScriptHandler; |
| 44 | |
| 45 | public final class MainActivity extends Activity { |
| 46 | private static final int PICK_INVITATION = 41; |
| 47 | private final ExecutorService worker = Executors.newSingleThreadExecutor(); |
| 48 | private SharedPreferences trust; |
| 49 | private HostCredentials credentials; |
| 50 | private DeviceKey device; |
| 51 | private String fingerprint = ""; |
| 52 | private Invitation invitation; |
| 53 | private Invitation.Saved imported; |
| 54 | private WebView browser; |
| 55 | private final Map<String, ConnectedDevice> connections = new LinkedHashMap<>(); |
| 56 | private ConnectedDevice activeDevice; |
| 57 | private boolean viewingWorkspace; |
| 58 | private boolean openArchivedAfterConnect; |
| 59 | private static final class ConnectedDevice { |
| 60 | final String id; |
| 61 | final String hostKey; |
| 62 | final Client client; |
| 63 | final Uri launch; |
| 64 | WebView view; |
| 65 | ScriptHandler script; |
| 66 | String name; |
| 67 | ConnectedDevice(String hostKey, Client client, Uri launch, String name) { |
| 68 | this.id=java.util.UUID.randomUUID().toString(); this.hostKey=hostKey; |
| 69 | this.client=client; this.launch=launch; this.name=name; |
| 70 | } |
| 71 | } |
| 72 | private enum Page { HOME, SETTINGS, HOST, RELAY, PAIR, CODE } |
| 73 | private Page page = Page.HOME; |
| 74 | private FrameLayout root; |
| 75 | private LinearLayout form; |
| 76 | private FrameLayout home; |
| 77 | private View overlay; |
| 78 | private EditText relayField, pinField; |
| 79 | private TextView localPin, status, inviteStatus; |
| 80 | private CheckBox verified; |
| 81 | private Switch customRelay; |
| 82 | private Button connect, forgetHost; |
| 83 | private boolean busy; |
| 84 | private int generation; |
| 85 | private MobileTheme palette; |
| 86 | private SharedPreferences appearance; |
| 87 | private static final int SCAN = 42; |
| 88 | |
| 89 | private void rememberRelay(String relay) { |
| 90 | trust.edit().putString("preferred-relay", relay).apply(); |
| 91 | } |
| 92 | private String preferredRelay() { |
| 93 | return trust.getString("preferred-relay", trust.getString("relay", Cagemobile.defaultRelay())); |
| 94 | } |
| 95 | private static String deviceModel() { |
| 96 | String model = Build.MODEL.trim(); |
| 97 | String brand = Build.MANUFACTURER.trim(); |
| 98 | if (brand.isEmpty() || model.regionMatches(true, 0, brand, 0, brand.length())) return model; |
| 99 | return Character.toUpperCase(brand.charAt(0)) + brand.substring(1) + " " + model; |
| 100 | } |
| 101 | private String selectedRelay() throws Exception { |
| 102 | return customRelay.isChecked() ? Invitation.relay(relayField.getText().toString()) : Cagemobile.defaultRelay(); |
| 103 | } |
| 104 | private void displayRelay(String value) { |
| 105 | boolean custom = !Cagemobile.defaultRelay().equals(value); |
| 106 | customRelay.setChecked(custom); |
| 107 | relayField.setText(custom ? value : ""); |
| 108 | relayField.setVisibility(custom ? View.VISIBLE : View.GONE); |
| 109 | } |
| 110 | private void pairScan(String code) { |
| 111 | if (busy) return; |
| 112 | if (device == null) { status.setText("设备密钥尚未就绪,请稍后重试。"); return; } |
| 113 | String relay = preferredRelay(); |
| 114 | int attempt = ++generation; |
| 115 | setConnecting(true); |
| 116 | status.setText("正在与电脑配对…"); |
| 117 | worker.execute(() -> { |
| 118 | try { |
| 119 | Invitation.Saved saved = new Invitation.Saved(new JSONObject(Cagemobile.pair(code, relay, device))); |
| 120 | credentials.save(saved.relay, saved.pin, saved.lookup); |
| 121 | rememberRelay(saved.relay); |
| 122 | runOnUiThread(() -> { |
| 123 | if (generation != attempt) return; |
| 124 | invitation = null; |
| 125 | imported = null; |
| 126 | setConnecting(false); |
| 127 | connect(); |
| 128 | }); |
| 129 | } catch (Exception e) { |
| 130 | runOnUiThread(() -> { |
| 131 | if (generation != attempt) return; |
| 132 | setConnecting(false); |
| 133 | status.setText("配对未完成。请确认两端使用同一中继,再用电脑上新生成的二维码或配对码重试。"); |
| 134 | }); |
| 135 | } |
| 136 | }); |
| 137 | } |
| 138 | |
| 139 | @Override public void onCreate(Bundle state) { |
| 140 | super.onCreate(state); |
| 141 | trust = getSharedPreferences("verified-host", MODE_PRIVATE); |
| 142 | appearance = getSharedPreferences("appearance", MODE_PRIVATE); |
| 143 | palette = MobileTheme.apply(this, themeMode()); |
| 144 | credentials = new HostCredentials(trust); |
| 145 | showSetup(); |
| 146 | if (state != null) { |
| 147 | String restoredPage = state.getString("page", Page.HOME.name()); |
| 148 | Page restored = "ENVIRONMENT".equals(restoredPage) ? Page.HOME : Page.valueOf(restoredPage); |
| 149 | if (restored == Page.PAIR || restored == Page.CODE) showPair(restored == Page.CODE); |
| 150 | if (restored == Page.SETTINGS) showSettings(false); |
| 151 | if (restored == Page.HOST || restored == Page.RELAY) showAdvanced(restored); |
| 152 | } |
| 153 | worker.execute(() -> { |
| 154 | try { |
| 155 | DeviceKey key = new DeviceKey(); |
| 156 | String pin = Cagemobile.fingerprint(key); |
| 157 | runOnUiThread(() -> { |
| 158 | if (isDestroyed()) return; |
| 159 | device = key; |
| 160 | fingerprint = pin; |
| 161 | if (localPin != null) localPin.setText(pin); |
| 162 | }); |
| 163 | } catch (Exception e) { |
| 164 | runOnUiThread(() -> { |
| 165 | if (!isDestroyed()) status.setText("无法使用 Android Keystore 设备密钥。"); |
| 166 | }); |
| 167 | } |
| 168 | }); |
| 169 | } |
| 170 | @Override protected void onSaveInstanceState(Bundle saved) { |
| 171 | super.onSaveInstanceState(saved); |
| 172 | saved.putString("page", page.name()); |
| 173 | } |
| 174 | |
| 175 | private int dp(int value) { return Math.round(getResources().getDisplayMetrics().density * value); } |
| 176 | private String themeMode() { return appearance.getString("theme", "system"); } |
| 177 | private void insets(View root) { |
| 178 | root.setOnApplyWindowInsetsListener((v, w) -> { |
| 179 | v.setPadding(w.getSystemWindowInsetLeft(), w.getSystemWindowInsetTop(), w.getSystemWindowInsetRight(), w.getSystemWindowInsetBottom()); |
| 180 | return w.consumeSystemWindowInsets(); |
| 181 | }); |
| 182 | root.requestApplyInsets(); |
| 183 | } |
| 184 | private LinearLayout column() { |
| 185 | LinearLayout group = new LinearLayout(this); |
| 186 | group.setOrientation(LinearLayout.VERTICAL); |
| 187 | return group; |
| 188 | } |
| 189 | private GradientDrawable surface(int color, int radius, boolean outline) { |
| 190 | GradientDrawable shape = new GradientDrawable(); |
| 191 | shape.setColor(color); |
| 192 | shape.setCornerRadius(dp(radius)); |
| 193 | if (outline) shape.setStroke(dp(1), palette.line); |
| 194 | return shape; |
| 195 | } |
| 196 | private Drawable pressable(int color, int radius, boolean outline) { |
| 197 | return new RippleDrawable(ColorStateList.valueOf(palette.dark ? 0x14ffffff : 0x0d000000), surface(color, radius, outline), null); |
| 198 | } |
| 199 | private TextView text(String value, int size, int color) { |
| 200 | TextView view = new TextView(this); |
| 201 | view.setText(value); |
| 202 | view.setTextSize(size); |
| 203 | view.setTextColor(color); |
| 204 | return view; |
| 205 | } |
| 206 | private TextView label(String value, int size) { |
| 207 | TextView view = text(value, size, palette.muted); |
| 208 | view.setPadding(0, dp(12), 0, dp(3)); |
| 209 | form.addView(view); |
| 210 | return view; |
| 211 | } |
| 212 | private Button button(LinearLayout parent, String name, boolean primary, View.OnClickListener action) { |
| 213 | Button view = new Button(this); |
| 214 | view.setText(name); |
| 215 | view.setAllCaps(false); |
| 216 | view.setTextSize(16); |
| 217 | view.setTextColor(primary ? palette.onAction : palette.ink); |
| 218 | view.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); |
| 219 | view.setStateListAnimator(null); |
| 220 | view.setBackground(pressable(primary ? palette.action : palette.soft, 14, false)); |
| 221 | view.setOnClickListener(action); |
| 222 | LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-1, dp(52)); |
| 223 | lp.topMargin = dp(8); |
| 224 | parent.addView(view, lp); |
| 225 | return view; |
| 226 | } |
| 227 | private ImageButton icon(String resource, String name, View.OnClickListener action) { |
| 228 | ImageButton view = new ImageButton(this); |
| 229 | view.setImageResource(getResources().getIdentifier("cage_" + resource, "drawable", getPackageName())); |
| 230 | view.setContentDescription(name); |
| 231 | view.setColorFilter(palette.ink); |
| 232 | view.setScaleType(ImageView.ScaleType.CENTER); |
| 233 | view.setBackground(pressable(palette.soft, 24, false)); |
| 234 | view.setOnClickListener(action); |
| 235 | return view; |
| 236 | } |
| 237 | private View connectComputerButton(View.OnClickListener action) { |
| 238 | LinearLayout view = new LinearLayout(this); |
| 239 | view.setOrientation(LinearLayout.HORIZONTAL); |
| 240 | view.setGravity(Gravity.CENTER); |
| 241 | view.setPadding(dp(16), 0, dp(16), 0); |
| 242 | view.setBackground(pressable(palette.action, 14, false)); |
| 243 | view.setFocusable(true); |
| 244 | view.setContentDescription("连接电脑"); |
| 245 | view.setOnClickListener(action); |
| 246 | view.setAccessibilityDelegate(new View.AccessibilityDelegate() { |
| 247 | @Override public void onInitializeAccessibilityNodeInfo(View host, android.view.accessibility.AccessibilityNodeInfo info) { |
| 248 | super.onInitializeAccessibilityNodeInfo(host, info); |
| 249 | info.setClassName(Button.class.getName()); |
| 250 | } |
| 251 | }); |
| 252 | ImageView computer = image("cage_computer"); |
| 253 | computer.setColorFilter(palette.onAction); |
| 254 | view.addView(computer, dp(22), dp(22)); |
| 255 | TextView title = text("连接电脑", 16, palette.onAction); |
| 256 | title.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); |
| 257 | title.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); |
| 258 | LinearLayout.LayoutParams caption = new LinearLayout.LayoutParams(-2, -2); |
| 259 | caption.setMarginStart(dp(10)); |
| 260 | view.addView(title, caption); |
| 261 | return view; |
| 262 | } |
| 263 | private EditText field(String hint, String value) { |
| 264 | EditText input = new EditText(this); |
| 265 | input.setSingleLine(); |
| 266 | input.setTextSize(16); |
| 267 | input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); |
| 268 | input.setHint(hint); |
| 269 | input.setText(value); |
| 270 | form.addView(input); |
| 271 | return input; |
| 272 | } |
| 273 | private void statusView() { |
| 274 | status = label("", 14); |
| 275 | status.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE); |
| 276 | status.setMinHeight(dp(22)); |
| 277 | } |
| 278 | private void layout(Page next) { |
| 279 | page = next; |
| 280 | overlay = null; |
| 281 | root = new FrameLayout(this); |
| 282 | root.setBackgroundColor(palette.bg); |
| 283 | setContentView(root); |
| 284 | insets(root); |
| 285 | localPin = null; |
| 286 | } |
| 287 | private ImageView image(String resource) { |
| 288 | ImageView img = new ImageView(this); |
| 289 | img.setImageResource(getResources().getIdentifier(resource, "drawable", getPackageName())); |
| 290 | img.setScaleType(ImageView.ScaleType.FIT_CENTER); |
| 291 | img.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); |
| 292 | return img; |
| 293 | } |
| 294 | private void showSetup() { |
| 295 | viewingWorkspace = false; |
| 296 | if (browser != null) browser.onPause(); |
| 297 | layout(Page.HOME); |
| 298 | ScrollView scroll = new ScrollView(this); |
| 299 | scroll.setFillViewport(true); |
| 300 | root.addView(scroll, -1, -1); |
| 301 | FrameLayout body = new FrameLayout(this); |
| 302 | body.setMinimumHeight(dp(440)); |
| 303 | scroll.addView(body, new ScrollView.LayoutParams(-1, -2)); |
| 304 | home = body; |
| 305 | FrameLayout.LayoutParams gear = new FrameLayout.LayoutParams(dp(48), dp(48), Gravity.TOP | Gravity.RIGHT); |
| 306 | gear.setMargins(dp(18), dp(12), dp(18), 0); |
| 307 | body.addView(icon("gear", "设置", v -> showSettings(false)), gear); |
| 308 | |
| 309 | form = column(); |
| 310 | form.setGravity(Gravity.CENTER); |
| 311 | LinearLayout homeForm = form; |
| 312 | |
| 313 | form.setPadding(0, dp(32), 0, 0); |
| 314 | FrameLayout.LayoutParams hero = new FrameLayout.LayoutParams(dp(276), -2, Gravity.CENTER); |
| 315 | hero.leftMargin = dp(24); |
| 316 | hero.rightMargin = dp(24); |
| 317 | body.addView(form, hero); |
| 318 | ImageView mark = image("cage_icon"); |
| 319 | mark.setBackground(surface(palette.panel, 18, false)); |
| 320 | mark.setClipToOutline(true); |
| 321 | form.addView(mark, dp(120), dp(120)); |
| 322 | TextView title = text("Cage", 38, palette.ink); |
| 323 | title.setTypeface(Typeface.DEFAULT, Typeface.BOLD); |
| 324 | title.setGravity(Gravity.CENTER); |
| 325 | title.setPadding(0, dp(8), 0, dp(52)); |
| 326 | form.addView(title); |
| 327 | LinearLayout.LayoutParams action = new LinearLayout.LayoutParams(-1, dp(60)); |
| 328 | action.topMargin = dp(8); |
| 329 | form.addView(connectComputerButton(v -> showPair(false)), action); |
| 330 | statusView(); |
| 331 | body.addOnLayoutChangeListener((view, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> { |
| 332 | int height = bottom - top; |
| 333 | if (height == oldBottom - oldTop && right - left == oldRight - oldLeft) return; |
| 334 | hero.width = Math.min(dp(276), Math.max(0, right - left - dp(48))); |
| 335 | homeForm.setLayoutParams(hero); |
| 336 | int spacing = Math.min(dp(60), Math.max(dp(28), Math.round(height * 0.075f))) + dp(32); |
| 337 | title.setPadding(0, dp(8), 0, spacing - dp(8)); |
| 338 | }); |
| 339 | } |
| 340 | private void closeSheet() { |
| 341 | if (busy) return; |
| 342 | showSetup(); |
| 343 | } |
| 344 | private void showPair(boolean code) { |
| 345 | boolean opening = overlay == null; |
| 346 | if (overlay != null) root.removeView(overlay); |
| 347 | page = code ? Page.CODE : Page.PAIR; |
| 348 | home.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); |
| 349 | home.setDescendantFocusability(android.view.ViewGroup.FOCUS_BLOCK_DESCENDANTS); |
| 350 | FrameLayout layer = new FrameLayout(this); |
| 351 | overlay = layer; |
| 352 | root.addView(layer, -1, -1); |
| 353 | View shade = new View(this); |
| 354 | shade.setBackgroundColor(0x64000000); |
| 355 | shade.setOnClickListener(v -> closeSheet()); |
| 356 | shade.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); |
| 357 | shade.setFocusable(false); |
| 358 | layer.addView(shade, -1, -1); |
| 359 | ScrollView scroll = new ScrollView(this); |
| 360 | scroll.setFillViewport(false); |
| 361 | scroll.setBackground(surface(palette.panel, 26, false)); |
| 362 | scroll.setClickable(true); |
| 363 | FrameLayout.LayoutParams sheet = new FrameLayout.LayoutParams(Math.min(getResources().getDisplayMetrics().widthPixels, dp(500)), -2, |
| 364 | Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL); |
| 365 | sheet.setMargins(dp(8), dp(12), dp(8), dp(8)); |
| 366 | sheet.width = Math.min(sheet.width - dp(16), dp(500)); |
| 367 | layer.addView(scroll, sheet); |
| 368 | form = column(); |
| 369 | form.setPadding(dp(20), dp(14), dp(20), dp(14)); |
| 370 | scroll.addView(form); |
| 371 | FrameLayout heading = new FrameLayout(this); |
| 372 | form.addView(heading, -1, dp(48)); |
| 373 | TextView title = text(code ? "配对码" : "连接电脑", 24, palette.ink); |
| 374 | title.setTypeface(Typeface.DEFAULT, Typeface.BOLD); |
| 375 | heading.addView(title, new FrameLayout.LayoutParams(-2, -2, Gravity.LEFT | Gravity.CENTER_VERTICAL)); |
| 376 | if (!code) { |
| 377 | form.addView(image("pair_devices"), -1, dp(112)); |
| 378 | label("在电脑的「设置 → 远程连接」中生成配对二维码或配对码。", 14); |
| 379 | button(form, "扫码连接", true, v -> startActivityForResult(new Intent(this, ScanActivity.class), SCAN)); |
| 380 | button(form, "使用配对码", false, v -> showPair(true)); |
| 381 | } else { |
| 382 | label("粘贴电脑上复制的一次性配对码。", 15); |
| 383 | EditText manualCode = field("一次性配对码", ""); |
| 384 | button(form, "连接电脑", true, v -> { |
| 385 | String value = manualCode.getText().toString().trim(); |
| 386 | if (value.isEmpty()) { status.setText("请粘贴配对码。"); return; } |
| 387 | manualCode.setText(""); |
| 388 | android.view.inputmethod.InputMethodManager ime = (android.view.inputmethod.InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); |
| 389 | ime.hideSoftInputFromWindow(manualCode.getWindowToken(), 0); |
| 390 | pairScan(value); |
| 391 | }); |
| 392 | button(form, "返回配对方式", false, v -> showPair(false)); |
| 393 | } |
| 394 | if (!code && !connections.isEmpty()) { |
| 395 | label("已连接的设备", 15); |
| 396 | label("长按设备可取消连接", 14); |
| 397 | for (ConnectedDevice connected : connections.values()) { |
| 398 | Button entry = button(form, connected.name + " · 进入", false, v -> enterDevice(connected)); |
| 399 | entry.setOnLongClickListener(v -> {confirmDisconnect(connected); return true;}); |
| 400 | } |
| 401 | } |
| 402 | if (credentials.saved() && !code) button(form, "重新连接已配对电脑", false, v -> connect()); |
| 403 | statusView(); |
| 404 | form.setFocusableInTouchMode(true); |
| 405 | form.requestFocus(); |
| 406 | if (opening && android.animation.ValueAnimator.areAnimatorsEnabled()) { |
| 407 | shade.setAlpha(0f); |
| 408 | scroll.getViewTreeObserver().addOnPreDrawListener(new android.view.ViewTreeObserver.OnPreDrawListener() { |
| 409 | @Override public boolean onPreDraw() { |
| 410 | scroll.getViewTreeObserver().removeOnPreDrawListener(this); |
| 411 | if (overlay != layer) return true; |
| 412 | |
| 413 | scroll.setTranslationY(scroll.getHeight() + sheet.bottomMargin); |
| 414 | scroll.animate().translationY(0).setDuration(300) |
| 415 | .setInterpolator(new android.view.animation.PathInterpolator(0.2f, 0f, 0f, 1f)).start(); |
| 416 | shade.animate().alpha(1f).setDuration(200).start(); |
| 417 | return true; |
| 418 | } |
| 419 | }); |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | private void settingsPage(Page next, String name, Runnable back) { |
| 424 | layout(next); |
| 425 | ScrollView scroll = new ScrollView(this); |
| 426 | root.addView(scroll, -1, -1); |
| 427 | form = column(); |
| 428 | form.setPadding(dp(22), dp(14), dp(22), dp(28)); |
| 429 | form.setFocusableInTouchMode(true); |
| 430 | scroll.addView(form); |
| 431 | form.addView(icon("back", "返回", v -> back.run()), dp(48), dp(48)); |
| 432 | TextView title = text(name, 32, palette.ink); |
| 433 | title.setTypeface(Typeface.DEFAULT, Typeface.BOLD); |
| 434 | title.setPadding(0, dp(26), 0, dp(18)); |
| 435 | form.addView(title); |
| 436 | } |
| 437 | private Button row(String title, View.OnClickListener listener) { |
| 438 | Button b = button(form, title, false, listener); |
| 439 | b.setGravity(Gravity.CENTER_VERTICAL | Gravity.START); |
| 440 | b.setPadding(dp(20), 0, dp(16), 0); |
| 441 | b.setBackground(pressable(palette.panel, 14, true)); |
| 442 | return b; |
| 443 | } |
| 444 | private static final String[] THEMES = {"system", "light", "dark"}; |
| 445 | private static final String[] THEME_NAMES = {"跟随系统", "浅色", "深色"}; |
| 446 | private void showSettings(boolean focusTheme) { |
| 447 | settingsPage(Page.SETTINGS, "设置", this::showSetup); |
| 448 | label("外观", 14); |
| 449 | int index = java.util.Arrays.asList(THEMES).indexOf(themeMode()); |
| 450 | LinearLayout options = column(); |
| 451 | String current = "主题 · " + THEME_NAMES[Math.max(0, index)]; |
| 452 | Button chooser = row(current + " ▾", v -> { |
| 453 | boolean opening = options.getVisibility() != View.VISIBLE; |
| 454 | options.setVisibility(opening ? View.VISIBLE : View.GONE); |
| 455 | ((Button)v).setText(current + (opening ? " ▴" : " ▾")); |
| 456 | }); |
| 457 | form.addView(options); |
| 458 | options.setVisibility(View.GONE); |
| 459 | for (int i = 0; i < THEMES.length; i++) { |
| 460 | String value = THEMES[i]; |
| 461 | Button choice = button(options, (i == index ? "✓ " : "") + THEME_NAMES[i], false, v -> { |
| 462 | appearance.edit().putString("theme", value).apply(); |
| 463 | palette = MobileTheme.apply(this, value); |
| 464 | showSettings(!v.isInTouchMode()); |
| 465 | }); |
| 466 | choice.setSelected(i == index); |
| 467 | } |
| 468 | label("远程连接", 14); |
| 469 | row("已归档会话", v -> openArchivedSessions()); |
| 470 | row("中继设置", v -> showAdvanced(Page.RELAY)); |
| 471 | row("主机与指纹", v -> showAdvanced(Page.HOST)); |
| 472 | statusView(); |
| 473 | if (focusTheme) chooser.requestFocus(); |
| 474 | } |
| 475 | |
| 476 | private void showAdvanced(Page next) { |
| 477 | boolean host = next == Page.HOST; |
| 478 | settingsPage(next, host ? "主机与指纹" : "中继设置", () -> showSettings(false)); |
| 479 | verified = new CheckBox(this); |
| 480 | customRelay = new Switch(this); |
| 481 | customRelay.setText("使用自建中继"); |
| 482 | form.addView(customRelay, -1, dp(48)); |
| 483 | relayField = field("自建 VPS 的 HTTPS 地址", ""); |
| 484 | customRelay.setOnCheckedChangeListener((view, enabled) -> { |
| 485 | relayField.setVisibility(enabled ? View.VISIBLE : View.GONE); |
| 486 | verified.setChecked(false); |
| 487 | }); |
| 488 | displayRelay(imported != null && host ? imported.relay : preferredRelay()); |
| 489 | if (!host) { |
| 490 | label("关闭自建中继后,使用 Cage 官方中继。", 14); |
| 491 | button(form, "保存中继设置", true, v -> { |
| 492 | try { rememberRelay(selectedRelay()); status.setText("中继设置已保存。"); } |
| 493 | catch (Exception e) { status.setText("请填写有效的 HTTPS 地址。"); } |
| 494 | }); |
| 495 | statusView(); |
| 496 | return; |
| 497 | } |
| 498 | label("这台手机的指纹", 15); |
| 499 | localPin = label(fingerprint.isEmpty() ? "正在读取设备密钥…" : fingerprint, 14); |
| 500 | localPin.setTypeface(Typeface.MONOSPACE); |
| 501 | localPin.setTextIsSelectable(true); |
| 502 | button(form, "复制手机指纹", false, v -> { |
| 503 | if (fingerprint.isEmpty()) return; |
| 504 | ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); |
| 505 | clipboard.setPrimaryClip(ClipData.newPlainText("Cage 手机指纹", fingerprint)); |
| 506 | status.setText("手机指纹已复制,请在电脑上核对并信任。"); |
| 507 | }); |
| 508 | label("电脑指纹", 15); |
| 509 | pinField = field("sha256:…", imported != null ? imported.pin : trust.getString("pin", "")); |
| 510 | verified.setText("我已与电脑上独立显示的指纹核对"); |
| 511 | form.addView(verified); |
| 512 | TextWatcher changed = new TextWatcher() { |
| 513 | public void beforeTextChanged(CharSequence s, int start, int count, int after) {} |
| 514 | public void onTextChanged(CharSequence s, int start, int before, int count) { verified.setChecked(false); } |
| 515 | public void afterTextChanged(Editable text) {} |
| 516 | }; |
| 517 | pinField.addTextChangedListener(changed); |
| 518 | relayField.addTextChangedListener(changed); |
| 519 | button(form, "保存已核对的主机", true, v -> saveVerified()); |
| 520 | forgetHost = button(form, "忘记主机", false, v -> new AlertDialog.Builder(this) |
| 521 | .setMessage("移除这台电脑的地址、指纹和重连凭据?") |
| 522 | .setNegativeButton("取消", null).setPositiveButton("忘记主机", (dialog, which) -> forget()).show()); |
| 523 | forgetHost.setVisibility(trust.contains("pin") ? View.VISIBLE : View.GONE); |
| 524 | inviteStatus = label(imported != null ? "请与电脑独立显示的指纹核对,再保存主机。" : |
| 525 | invitation != null ? "已导入本次临时邀请。" : |
| 526 | credentials.saved() ? "这台电脑已保存,可以直接重新连接。" : "导入电脑生成的连接文件或临时邀请。", 14); |
| 527 | button(form, "导入连接文件", false, v -> { |
| 528 | Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*"); |
| 529 | startActivityForResult(intent, PICK_INVITATION); |
| 530 | }); |
| 531 | connect = button(form, credentials.saved() ? "重新连接" : "连接工作台", false, v -> connect()); |
| 532 | statusView(); |
| 533 | } |
| 534 | |
| 535 | private void saveVerified() { |
| 536 | if (!verified.isChecked()) { status.setText("请先在电脑上核对指纹。"); return; } |
| 537 | final String relay, pin; |
| 538 | try { relay = selectedRelay(); pin = Invitation.pin(pinField.getText().toString()); } |
| 539 | catch (Exception e) { status.setText("中继地址或电脑指纹格式无效。"); return; } |
| 540 | Invitation.Saved record = imported; |
| 541 | if (record != null && (!record.relay.equals(relay) || !record.pin.equals(pin))) { status.setText("填写内容与导入的连接文件不一致,请重新核对。"); return; } |
| 542 | int attempt = ++generation; |
| 543 | setConnecting(true); |
| 544 | worker.execute(() -> { |
| 545 | try { |
| 546 | credentials.save(relay, pin, record == null ? null : record.lookup);rememberRelay(relay); |
| 547 | runOnUiThread(() -> { if (generation == attempt) { |
| 548 | imported = null; verified.setChecked(false); setConnecting(false); forgetHost.setVisibility(View.VISIBLE); |
| 549 | connect.setText(credentials.saved() && invitation == null ? "重新连接" : "连接工作台"); |
| 550 | if (credentials.saved() && invitation == null) inviteStatus.setText("这台电脑已保存,可以直接重新连接。"); |
| 551 | status.setText(credentials.saved() ? "已保存这台电脑,可以重新连接。" : "已保存主机指纹。"); |
| 552 | } }); |
| 553 | } catch (Exception e) { runOnUiThread(() -> { if (generation == attempt) { setConnecting(false); status.setText("无法安全保存主机,请解锁手机后重试。"); } }); } |
| 554 | }); |
| 555 | } |
| 556 | private void forget() { |
| 557 | int attempt = ++generation; setConnecting(true); |
| 558 | worker.execute(() -> { |
| 559 | try { |
| 560 | credentials.forget(); |
| 561 | runOnUiThread(() -> { if (generation == attempt) { invitation=null; imported=null; setConnecting(false); showAdvanced(Page.HOST); status.setText("已忘记主机。"); } }); |
| 562 | } catch (Exception e) { runOnUiThread(() -> { if (generation == attempt) { setConnecting(false); status.setText("移除未完成,请重试。"); } }); } |
| 563 | }); |
| 564 | } |
| 565 | |
| 566 | @Override protected void onActivityResult(int code, int result, Intent data) { |
| 567 | super.onActivityResult(code, result, data); |
| 568 | if (code == SCAN) { |
| 569 | if(result==RESULT_OK && data!=null) pairScan(data.getStringExtra("code")); |
| 570 | else if(data!=null && data.hasExtra("error"))status.setText(data.getStringExtra("error")); |
| 571 | return; |
| 572 | } |
| 573 | if (code != PICK_INVITATION || result != RESULT_OK || data == null || data.getData() == null) return; |
| 574 | Uri file = data.getData(); |
| 575 | if (!"content".equals(file.getScheme())) { status.setText("请选择设备文件应用中的邀请。"); return; } |
| 576 | int attempt = ++generation; |
| 577 | invitation = null; imported = null; verified.setChecked(false); setConnecting(true); |
| 578 | worker.execute(() -> { |
| 579 | try (InputStream input = getContentResolver().openInputStream(file)) { |
| 580 | JSONObject object = Invitation.read(input); |
| 581 | Invitation.Saved saved = object.has("version") ? new Invitation.Saved(object) : null; |
| 582 | Invitation item = saved == null ? Invitation.room(object) : null; |
| 583 | runOnUiThread(() -> { if (attempt == generation) { |
| 584 | setConnecting(false); invitation = item; imported = saved; status.setText(""); |
| 585 | if (saved != null) { |
| 586 | displayRelay(saved.relay); pinField.setText(saved.pin); verified.setChecked(false); |
| 587 | inviteStatus.setText("请与电脑独立显示的指纹核对,再保存主机。"); |
| 588 | } else { inviteStatus.setText("已导入本次临时邀请。"); } |
| 589 | connect.setText("连接工作台"); |
| 590 | } }); |
| 591 | } catch (Exception e) { |
| 592 | runOnUiThread(() -> { if (attempt == generation) { setConnecting(false); inviteStatus.setText("文件无效或临时邀请已过期,请重新导入。"); } }); |
| 593 | } |
| 594 | }); |
| 595 | } |
| 596 | |
| 597 | private void connect() { |
| 598 | connect(false); |
| 599 | } |
| 600 | private void connect(boolean archivedEntry) { |
| 601 | if (busy) return; |
| 602 | openArchivedAfterConnect = archivedEntry; |
| 603 | final String relay, pin; |
| 604 | try { |
| 605 | relay = page == Page.HOST ? selectedRelay() : trust.getString("relay", preferredRelay()); |
| 606 | pin = Invitation.pin(page == Page.HOST ? pinField.getText().toString() : trust.getString("pin", "")); |
| 607 | } catch (Exception e) { status.setText("请在「设置 → 主机与指纹」保存电脑指纹。"); return; } |
| 608 | if ((page == Page.HOST && imported != null) || !credentials.matches(relay,pin)) { status.setText("请先核对并保存这台主机。"); return; } |
| 609 | ConnectedDevice existing = connections.get(relay + "\n" + pin); |
| 610 | if (existing != null) { |
| 611 | enterDevice(existing); |
| 612 | if (openArchivedAfterConnect) { |
| 613 | openArchivedAfterConnect = false; |
| 614 | browser.evaluateJavascript("window.dispatchEvent(new Event('cage-open-archives'))", null); |
| 615 | } |
| 616 | return; |
| 617 | } |
| 618 | if (device == null) { status.setText("设备密钥尚未就绪。"); return; } |
| 619 | Invitation item = page == Page.HOST ? invitation : null; |
| 620 | if (item == null && !credentials.saved()) { status.setText("请导入连接文件或有效的临时邀请。"); return; } |
| 621 | if (item != null && !item.expiry.isAfter(Instant.now())) { invitation=null; status.setText("临时邀请已过期,请重新连接或导入新邀请。"); return; } |
| 622 | invitation = null; |
| 623 | if (item != null) inviteStatus.setText("本次邀请已用于连接。"); |
| 624 | int attempt = ++generation; setConnecting(true); status.setText("正在验证电脑并连接…"); |
| 625 | worker.execute(() -> { |
| 626 | Client opened = null; |
| 627 | try { |
| 628 | String directory = extractUI(); |
| 629 | opened = item == null |
| 630 | ? Cagemobile.openSaved(relay, credentials.lookup(relay, pin), pin, device) |
| 631 | : Cagemobile.open(relay, item.room, item.token, pin, device); |
| 632 | if (item == null) opened.reportDevice("android", deviceModel()); |
| 633 | String launch = opened.startUI(directory); |
| 634 | Uri url = Uri.parse(launch); |
| 635 | if (!"http".equals(url.getScheme()) || !"127.0.0.1".equals(url.getHost()) || url.getPort()<1 || url.getUserInfo()!=null) throw new IOException(); |
| 636 | Client connected = opened; |
| 637 | runOnUiThread(() -> { |
| 638 | if (attempt != generation || isDestroyed()) { close(connected); return; } |
| 639 | setConnecting(false); |
| 640 | ConnectedDevice next = new ConnectedDevice(relay + "\n" + pin, connected, url, |
| 641 | "电脑 " + (connections.size() + 1)); |
| 642 | connections.put(next.hostKey, next); |
| 643 | createBrowser(next); |
| 644 | enterDevice(next); |
| 645 | broadcastDevices(); |
| 646 | }); |
| 647 | } catch (Exception e) { |
| 648 | close(opened); |
| 649 | runOnUiThread(() -> { if (attempt == generation) { |
| 650 | setConnecting(false); if (page == Page.HOST) connect.setText(credentials.saved() ? "重新连接" : "连接工作台"); |
| 651 | status.setText(item == null ? "连接未完成。请确认电脑上的连接服务正在运行,再点重新连接。若已更换凭据,请导入新的连接文件。" : "连接未完成。请核对双方指纹与网络,再导入新邀请。"); |
| 652 | } }); |
| 653 | } |
| 654 | }); |
| 655 | } |
| 656 | private void setConnecting(boolean connecting) { |
| 657 | busy = connecting; |
| 658 | enableActions(root, !connecting); |
| 659 | } |
| 660 | private static void enableActions(View view, boolean enabled) { |
| 661 | if (view instanceof android.view.ViewGroup) { |
| 662 | android.view.ViewGroup group = (android.view.ViewGroup)view; |
| 663 | for (int i = 0; i < group.getChildCount(); i++) enableActions(group.getChildAt(i), enabled); |
| 664 | } else if (view.isClickable() || view instanceof EditText) view.setEnabled(enabled); |
| 665 | } |
| 666 | private String extractUI() throws IOException { |
| 667 | File root = new File(getCacheDir(), "cage-mobile-ui"); |
| 668 | copyAssets(getAssets(), "mobile-ui", root); |
| 669 | return root.getAbsolutePath(); |
| 670 | } |
| 671 | private static void copyAssets(AssetManager assets, String path, File dest) throws IOException { |
| 672 | String[] children = assets.list(path); |
| 673 | if (children == null) throw new IOException("missing bundled assets"); |
| 674 | if (children.length == 0) { |
| 675 | try (InputStream input = assets.open(path); OutputStream output = new FileOutputStream(dest)) { |
| 676 | byte[] bytes = new byte[16384]; int n; |
| 677 | while ((n=input.read(bytes))!=-1) output.write(bytes,0,n); |
| 678 | } |
| 679 | return; |
| 680 | } |
| 681 | if (!dest.isDirectory() && !dest.mkdirs()) throw new IOException("asset storage unavailable"); |
| 682 | for (String child: children) copyAssets(assets,path+"/"+child,new File(dest,child)); |
| 683 | } |
| 684 | private static boolean allowed(Uri url, int port) { |
| 685 | return "http".equals(url.getScheme()) && "127.0.0.1".equals(url.getHost()) && url.getPort() == port && url.getUserInfo() == null; |
| 686 | } |
| 687 | private JSONObject deviceSnapshot(ConnectedDevice current) { |
| 688 | JSONObject state = new JSONObject(); |
| 689 | JSONArray devices = new JSONArray(); |
| 690 | try { |
| 691 | for (ConnectedDevice connected : connections.values()) { |
| 692 | JSONObject item = new JSONObject(); |
| 693 | item.put("id", connected.id); item.put("name", connected.name); devices.put(item); |
| 694 | } |
| 695 | state.put("current", current.id); state.put("devices", devices); |
| 696 | } catch (org.json.JSONException impossible) {throw new IllegalStateException(impossible);} |
| 697 | return state; |
| 698 | } |
| 699 | private String deviceScript(ConnectedDevice current) { |
| 700 | return "window.__cageDevices=" + deviceSnapshot(current).toString() + |
| 701 | ";window.dispatchEvent(new CustomEvent('cage-devices',{detail:window.__cageDevices}));"; |
| 702 | } |
| 703 | private void broadcastDevices() { |
| 704 | for (ConnectedDevice connected : connections.values()) { |
| 705 | if (connected.script != null) connected.script.remove(); |
| 706 | if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) |
| 707 | connected.script = WebViewCompat.addDocumentStartJavaScript(connected.view, deviceScript(connected), |
| 708 | java.util.Collections.singleton("http://127.0.0.1:" + connected.launch.getPort())); |
| 709 | if (connected.view.getUrl() != null && allowed(Uri.parse(connected.view.getUrl()), connected.launch.getPort())) |
| 710 | connected.view.evaluateJavascript(deviceScript(connected), null); |
| 711 | } |
| 712 | } |
| 713 | private void deviceCommand(ConnectedDevice source, String json) { |
| 714 | if (!connections.containsValue(source) || isDestroyed()) return; |
| 715 | try { |
| 716 | JSONObject command = new JSONObject(json); |
| 717 | String action = command.optString("action"); |
| 718 | if ("name".equals(action)) { |
| 719 | String name = command.optString("name").trim(); |
| 720 | if (!name.isEmpty() && name.length() <= 120 && !name.equals(source.name)) { |
| 721 | source.name = name; broadcastDevices(); |
| 722 | } |
| 723 | return; |
| 724 | } |
| 725 | if (!viewingWorkspace || source != activeDevice) return; |
| 726 | if ("home".equals(action)) showSetup(); |
| 727 | } catch (org.json.JSONException ignored) {} |
| 728 | } |
| 729 | private void createBrowser(ConnectedDevice connected) { |
| 730 | WebView view = new WebView(this); |
| 731 | connected.view = view; |
| 732 | WebView.setWebContentsDebuggingEnabled(false); |
| 733 | WebSettings settings = view.getSettings(); settings.setJavaScriptEnabled(true); settings.setAllowFileAccess(false); settings.setAllowContentAccess(false); |
| 734 | settings.setUserAgentString(settings.getUserAgentString() + " CageMobile/1"); |
| 735 | settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); |
| 736 | CookieManager.getInstance().setAcceptThirdPartyCookies(view,false); |
| 737 | final int port = connected.launch.getPort(); |
| 738 | java.util.Set<String> origins = java.util.Collections.singleton("http://127.0.0.1:" + port); |
| 739 | if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) { |
| 740 | WebViewCompat.addWebMessageListener(view, "CageDevices", origins, (web, message, origin, mainFrame, reply) -> { |
| 741 | if (message.getType() == androidx.webkit.WebMessageCompat.TYPE_STRING && mainFrame && |
| 742 | allowed(origin, port) && web.getUrl() != null && allowed(Uri.parse(web.getUrl()), port)) |
| 743 | runOnUiThread(() -> deviceCommand(connected, message.getData())); |
| 744 | }); |
| 745 | } |
| 746 | if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) |
| 747 | connected.script = WebViewCompat.addDocumentStartJavaScript(view, deviceScript(connected), origins); |
| 748 | view.setWebViewClient(new WebViewClient() { |
| 749 | @Override public void onPageFinished(WebView w, String url) { |
| 750 | if (allowed(Uri.parse(url), port)) w.evaluateJavascript(deviceScript(connected), null); |
| 751 | } |
| 752 | @Override public boolean shouldOverrideUrlLoading(WebView w, WebResourceRequest r) { |
| 753 | String command = r.getUrl().toString(); |
| 754 | if (r.isForMainFrame() && r.hasGesture() && w.getUrl() != null && allowed(Uri.parse(w.getUrl()), port)) { |
| 755 | if (command.equals("cage://home")) { w.post(() -> showSetup()); return true; } |
| 756 | } |
| 757 | return !allowed(r.getUrl(),port); |
| 758 | } |
| 759 | @Override public WebResourceResponse shouldInterceptRequest(WebView w, WebResourceRequest r) { |
| 760 | if (allowed(r.getUrl(),port)) return null; |
| 761 | return new WebResourceResponse("text/plain","UTF-8",403,"Forbidden",java.util.Collections.emptyMap(),new ByteArrayInputStream(new byte[0])); |
| 762 | } |
| 763 | }); |
| 764 | Uri launch = connected.launch; |
| 765 | if (openArchivedAfterConnect) { |
| 766 | launch = launch.buildUpon().appendQueryParameter("page", "archived").build(); |
| 767 | openArchivedAfterConnect = false; |
| 768 | } |
| 769 | view.loadUrl(launch.toString()); |
| 770 | } |
| 771 | private void openArchivedSessions() { |
| 772 | if (activeDevice != null && connections.containsValue(activeDevice)) { |
| 773 | enterDevice(activeDevice); |
| 774 | browser.evaluateJavascript("window.dispatchEvent(new Event('cage-open-archives'))", null); |
| 775 | } else { |
| 776 | connect(true); |
| 777 | } |
| 778 | } |
| 779 | private void enterDevice(ConnectedDevice selected) { |
| 780 | if (!connections.containsValue(selected)) return; |
| 781 | if (browser != null && browser != selected.view) browser.onPause(); |
| 782 | activeDevice = selected; browser = selected.view; viewingWorkspace = true; |
| 783 | LinearLayout pane = column(); |
| 784 | if (browser.getParent() instanceof android.view.ViewGroup) |
| 785 | ((android.view.ViewGroup)browser.getParent()).removeView(browser); |
| 786 | pane.addView(browser, new LinearLayout.LayoutParams(-1,0,1)); |
| 787 | setContentView(pane); insets(pane); browser.onResume(); broadcastDevices(); |
| 788 | } |
| 789 | private void confirmDisconnect(ConnectedDevice selected) { |
| 790 | Dialog dialog = new Dialog(this); |
| 791 | LinearLayout panel = column(); panel.setPadding(dp(22),dp(18),dp(22),dp(22)); |
| 792 | panel.setBackground(surface(palette.panel,26,false)); |
| 793 | TextView title = text("取消与“" + selected.name + "”的连接?",20,palette.ink); |
| 794 | title.setTypeface(Typeface.DEFAULT,Typeface.BOLD); panel.addView(title); |
| 795 | TextView explanation = text("设备将从当前连接列表移除,已保存的配对信息仍然保留。",14,palette.muted); |
| 796 | explanation.setPadding(0,dp(12),0,dp(12)); panel.addView(explanation); |
| 797 | button(panel,"取消连接",true,v -> {dialog.dismiss(); disconnectDevice(selected);}); |
| 798 | button(panel,"继续连接",false,v -> dialog.dismiss()); |
| 799 | dialog.setContentView(panel); |
| 800 | android.view.Window window = dialog.getWindow(); |
| 801 | if (window != null) { |
| 802 | window.setBackgroundDrawableResource(android.R.color.transparent); |
| 803 | window.setGravity(Gravity.BOTTOM); |
| 804 | window.setLayout(-1,-2); |
| 805 | } |
| 806 | dialog.show(); |
| 807 | if (window != null) window.setLayout(-1,-2); |
| 808 | } |
| 809 | private static void close(Client c) { if (c!=null) try { c.close(); } catch (Exception ignored) { } } |
| 810 | private void disconnectDevice(ConnectedDevice connected) { |
| 811 | if (connections.remove(connected.hostKey) == null) return; |
| 812 | if (connected.script != null) connected.script.remove(); |
| 813 | connected.view.stopLoading(); |
| 814 | if (connected.view.getParent() instanceof android.view.ViewGroup) |
| 815 | ((android.view.ViewGroup)connected.view.getParent()).removeView(connected.view); |
| 816 | connected.view.destroy(); |
| 817 | worker.execute(() -> close(connected.client)); |
| 818 | if (activeDevice == connected) { |
| 819 | browser = null; activeDevice = null; |
| 820 | if (viewingWorkspace) showSetup(); |
| 821 | } |
| 822 | if (page == Page.PAIR) showPair(false); |
| 823 | broadcastDevices(); |
| 824 | } |
| 825 | private void endSession() { |
| 826 | ++generation; invitation = null; |
| 827 | for (ConnectedDevice connected : new java.util.ArrayList<>(connections.values())) { |
| 828 | if (connected.script != null) connected.script.remove(); |
| 829 | connected.view.stopLoading(); connected.view.destroy(); |
| 830 | worker.execute(() -> close(connected.client)); |
| 831 | } |
| 832 | connections.clear(); browser = null; activeDevice = null; |
| 833 | } |
| 834 | @Override protected void onPause() { |
| 835 | if (viewingWorkspace && browser != null) browser.onPause(); |
| 836 | super.onPause(); |
| 837 | } |
| 838 | @Override protected void onResume() { |
| 839 | super.onResume(); |
| 840 | if (viewingWorkspace && browser != null) browser.onResume(); |
| 841 | } |
| 842 | @Override public void onBackPressed() { |
| 843 | if (busy) return; |
| 844 | if (viewingWorkspace && browser != null && browser.canGoBack()) browser.goBack(); |
| 845 | else if (viewingWorkspace) showSetup(); |
| 846 | else if (page == Page.CODE) showPair(false); |
| 847 | else if (page == Page.RELAY || page == Page.HOST) showSettings(false); |
| 848 | else if (page != Page.HOME) showSetup(); |
| 849 | else super.onBackPressed(); |
| 850 | } |
| 851 | @Override public void onDestroy() { endSession(); worker.shutdown(); super.onDestroy(); } |
| 852 | } |