import 'dart:io'; import '../utils/command_runner.dart'; /// 开机自启:mac 写 LaunchAgent(RunAtLoad 一次性——托盘退出不能被拉回,故不用 KeepAlive); /// Windows 写 HKCU Run 注册表键(reg 命令实现,免 win32 依赖)。 /// 自启指向当前可执行文件(Platform.resolvedExecutable),以安装位置为准。 class Autostart { static const macLabel = 'com.zax.desktop-plugin'; static const winRunName = 'ZaxDesktopPlugin'; static bool get isSupported => Platform.isMacOS || Platform.isWindows; static String? get _macPlistPath { final home = Platform.environment['HOME']; if (home == null) return null; return '$home/Library/LaunchAgents/$macLabel.plist'; } /// 自启是否已开启。 static Future isEnabled() async { if (Platform.isMacOS) { final path = _macPlistPath; return path != null && File(path).existsSync(); } if (Platform.isWindows) { final r = await runCommand( 'reg', ['query', r'HKCU\Software\Microsoft\Windows\CurrentVersion\Run', '/v', winRunName], tolerateExit: true, ); return r.contains(winRunName); } return false; } /// 开启自启(mac 顺带把 C# 助手的 LaunchAgent 状态返回,供向导提示端口关系)。 static Future enable() async { if (Platform.isMacOS) { final path = _macPlistPath; if (path == null) throw StateError('无法定位用户目录'); final exe = Platform.resolvedExecutable; await Directory(File(path).parent.path).create(recursive: true); await File(path).writeAsString(''' Label $macLabel ProgramArguments $exe RunAtLoad LaunchOnlyOnce '''); return; } if (Platform.isWindows) { final exe = Platform.resolvedExecutable; await runCommand('reg', [ 'add', r'HKCU\Software\Microsoft\Windows\CurrentVersion\Run', '/v', winRunName, '/t', 'REG_SZ', '/d', '"$exe"', '/f', ]); return; } throw UnsupportedError('当前平台不支持开机自启'); } static Future disable() async { if (Platform.isMacOS) { final path = _macPlistPath; if (path != null && File(path).existsSync()) { await File(path).delete(); } return; } if (Platform.isWindows) { await runCommand( 'reg', ['delete', r'HKCU\Software\Microsoft\Windows\CurrentVersion\Run', '/v', winRunName, '/f'], tolerateExit: true, // 不存在时也算关闭成功 ); return; } throw UnsupportedError('当前平台不支持开机自启'); } /// C# 版助手的 LaunchAgent 是否在(本机灰度共存提示用;mac only)。 static bool get legacyCsharpAgentInstalled { if (!Platform.isMacOS) return false; final home = Platform.environment['HOME']; return home != null && File('$home/Library/LaunchAgents/com.zax.cardprinteragent.plist').existsSync(); } }