Files
pangolin/client/lib/system_tray.dart
T
wangjia 31443d0fe7
ci-pangolin / Lint — shellcheck (push) Has been cancelled
ci-pangolin / OpenAPI Sync Check (push) Has been cancelled
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (push) Has been cancelled
ci-pangolin / Flutter — analyze + test (push) Has been cancelled
fix(client): 退出 Pangolin 时拆隧道(停内核),不再残留 sing-box/TUN
此前真退出(托盘退出 / Cmd+Q)走 windowManager.destroy(),从不先停内核,
而 sing-box 是 sudo root 子进程不随父进程退出 → 孤儿 + TUN 残留,得手动 pkill。

- system_tray:托盘「退出」前 await onBeforeQuit()(停内核)再 destroy。
- main:PangolinApp→ConsumerStatefulWidget,AppLifecycleListener.onExitRequested
  在 Cmd+Q 时先停内核再退;_teardownVpn 调 vpnBridge.stop()(SIGTERM→sing-box,
  拆 TUN),带 3s 超时兜底。
- 关窗口→隐藏托盘的路径不拆(保持连接,符合常驻语义)。

flutter analyze 0 error;116 tests passed。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 09:21:22 +08:00

72 lines
2.5 KiB
Dart

// system_tray.dart — 桌面端系统托盘 + 关闭即最小化到托盘。
//
// macOS/Windows/Linux:关闭主窗口不退出,而是隐藏到托盘;托盘图标点击/菜单
// 可重新显示或真正退出。移动端/web 不涉及。
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:tray_manager/tray_manager.dart';
import 'package:window_manager/window_manager.dart';
bool get isDesktop =>
!kIsWeb && (Platform.isMacOS || Platform.isWindows || Platform.isLinux);
class TrayService with TrayListener, WindowListener {
TrayService._();
static final TrayService instance = TrayService._();
/// 真正退出前的清理钩子(由 app 注册,用于先停内核拆隧道再退出)。
Future<void> Function()? onBeforeQuit;
/// 在 runApp 前调用(仅桌面端)。设置窗口拦截关闭 + 托盘图标与菜单。
Future<void> init() async {
await windowManager.ensureInitialized();
// 关闭窗口转为隐藏到托盘(见 onWindowClose)。
await windowManager.setPreventClose(true);
windowManager.addListener(this);
trayManager.addListener(this);
await trayManager.setIcon('assets/tray_icon.png');
await trayManager.setToolTip('穿山甲 Pangolin');
await trayManager.setContextMenu(Menu(items: [
MenuItem(key: 'show', label: '显示主界面'),
MenuItem.separator(),
MenuItem(key: 'quit', label: '退出'),
]));
}
Future<void> _show() async {
await windowManager.show();
await windowManager.focus();
}
// ── 托盘事件 ──────────────────────────────────────────────────
@override
void onTrayIconMouseDown() => _show();
@override
void onTrayIconRightMouseDown() => trayManager.popUpContextMenu();
@override
void onTrayMenuItemClick(MenuItem menuItem) async {
switch (menuItem.key) {
case 'show':
_show();
case 'quit':
// 退出前先停内核拆隧道(避免 sudo sing-box 孤儿 + TUN 残留)。
await onBeforeQuit?.call();
await windowManager.setPreventClose(false);
await windowManager.destroy();
}
}
// ── 窗口事件 ──────────────────────────────────────────────────
@override
void onWindowClose() async {
// 点关闭 → 隐藏到托盘而非退出(常驻保持隧道)。
if (await windowManager.isPreventClose()) {
await windowManager.hide();
}
}
}