|
| 1 | +// |
| 2 | +// ExitManager.swift |
| 3 | +// ClashX |
| 4 | +// |
| 5 | +// Copyright © 2024 west2online. All rights reserved. |
| 6 | +// |
| 7 | + |
| 8 | +import AppKit |
| 9 | +import Atomics |
| 10 | +import Foundation |
| 11 | +import RxSwift |
| 12 | + |
| 13 | + |
| 14 | +@MainActor |
| 15 | +final class ExitManager { |
| 16 | + static let shared = ExitManager() |
| 17 | + |
| 18 | + private let normalTimeout: TimeInterval = 5 |
| 19 | + private let forceTimeout: TimeInterval = 2 |
| 20 | + |
| 21 | + private var isTerminating = false |
| 22 | + private var forceQuitPending = false |
| 23 | + |
| 24 | + // MARK: - External API |
| 25 | + |
| 26 | + func requestQuit(force: Bool) { |
| 27 | + forceQuitPending = force |
| 28 | + #warning("Use thread 'global' to ensure 'Task' in 'applicationShouldTerminate' executes correctly. 💩💩💩") |
| 29 | + DispatchQueue.global(qos: .userInitiated).async { |
| 30 | + NSApp.terminate(nil) |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + func handleShouldTerminate() async -> Bool { |
| 35 | + guard !isTerminating else { |
| 36 | + return true |
| 37 | + } |
| 38 | + isTerminating = true |
| 39 | + |
| 40 | + let shouldForce = forceQuitPending |
| 41 | + forceQuitPending = false |
| 42 | + |
| 43 | + if !shouldForce { |
| 44 | + guard await confirmAction() else { |
| 45 | + isTerminating = false |
| 46 | + return false |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + ConfigManager.shared.proxyState.isTunModeEnabled = |
| 51 | + ConfigManager.shared.proxyState.isTunModeActive |
| 52 | + |
| 53 | + async let stopTask = stopMetaAndDisableTun(timeout: shouldForce ? forceTimeout : normalTimeout) |
| 54 | + |
| 55 | + removeTempFiles() |
| 56 | + |
| 57 | + guard let forceDisable = forceDisableForProxyCleanup() else { |
| 58 | + _ = await stopTask |
| 59 | + ConfigManager.shared.restoreSystemProxy = false |
| 60 | + Logger.log("ClashX quit without clean waiting") |
| 61 | + return true |
| 62 | + } |
| 63 | + |
| 64 | + Logger.log("ClashX quit need clean proxy setting") |
| 65 | + ConfigManager.shared.restoreSystemProxy = true |
| 66 | + prepareForTerminationWait() |
| 67 | + |
| 68 | + _ = await stopTask |
| 69 | + Logger.log("ClashX quit wait for clean up") |
| 70 | + |
| 71 | + let finished = await performProxyCleanup(forceDisable: forceDisable, timeout: shouldForce ? forceTimeout : normalTimeout) |
| 72 | + if finished { |
| 73 | + Logger.log("ClashX quit after clean up finish") |
| 74 | + } else { |
| 75 | + Logger.log("ClashX quit after clean up timeout") |
| 76 | + } |
| 77 | + |
| 78 | + return true |
| 79 | + } |
| 80 | + |
| 81 | + @MainActor |
| 82 | + func handleWillTerminate() async { |
| 83 | + UserDefaults.standard.set(0, forKey: "launch_fail_times") |
| 84 | + Logger.log("ClashX will terminate") |
| 85 | + ApiRequest.shared.prepareForTermination() |
| 86 | + } |
| 87 | + |
| 88 | + // MARK: - Private |
| 89 | + |
| 90 | + @MainActor |
| 91 | + private func confirmAction() -> Bool { |
| 92 | + if NSApp.activationPolicy() == .regular { |
| 93 | + let alert = NSAlert() |
| 94 | + alert.messageText = NSLocalizedString("Quit ClashX?", comment: "") |
| 95 | + alert.informativeText = NSLocalizedString("The active connections will be interrupted.", comment: "") |
| 96 | + alert.alertStyle = .informational |
| 97 | + alert.addButton(withTitle: NSLocalizedString("Quit", comment: "")) |
| 98 | + alert.addButton(withTitle: NSLocalizedString("Cancel", comment: "")) |
| 99 | + return alert.runModal() == .alertFirstButtonReturn |
| 100 | + } |
| 101 | + return true |
| 102 | + } |
| 103 | + |
| 104 | + private func stopMetaAndDisableTun(timeout: TimeInterval) async { |
| 105 | + let cancelled = ManagedAtomic<Bool>(false) |
| 106 | + await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in |
| 107 | + Task { |
| 108 | + let deadline = Date().addingTimeInterval(timeout) |
| 109 | + while Date() < deadline, !cancelled.load(ordering: .relaxed) { |
| 110 | + try? await Task.sleep(for: .milliseconds(100)) |
| 111 | + } |
| 112 | + if !cancelled.load(ordering: .relaxed) { |
| 113 | + cancelled.store(true, ordering: .relaxed) |
| 114 | + continuation.resume() |
| 115 | + } |
| 116 | + } |
| 117 | + Task { |
| 118 | + try? await PrivilegedHelperManager.shared.request( |
| 119 | + ProxyConfigHelperMessages.StopMeta()) |
| 120 | + try? await PrivilegedHelperManager.shared.request( |
| 121 | + ProxyConfigHelperMessages.UpdateTun( |
| 122 | + state: false, dns: ConfigManager.metaTunDNS)) |
| 123 | + if !cancelled.load(ordering: .relaxed) { |
| 124 | + cancelled.store(true, ordering: .relaxed) |
| 125 | + continuation.resume() |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + private func removeTempFiles() { |
| 132 | + try? FileManager.default.removeItem(atPath: Paths.tempPath() + "/cacheConfigs") |
| 133 | + try? FileManager.default.removeItem(atPath: Paths.localConfigPath(for: kSafeConfigName)) |
| 134 | + } |
| 135 | + |
| 136 | + private func forceDisableForProxyCleanup() -> Bool? { |
| 137 | + let shouldCleanSystemProxy = |
| 138 | + (ConfigManager.shared.proxyState.isSystemProxyEnabled && |
| 139 | + !ConfigManager.shared.proxyState.isSystemProxySetByOther) || |
| 140 | + NetworkChangeNotifier.isCurrentSystemSetToClash(looser: true) || |
| 141 | + NetworkChangeNotifier.hasInterfaceProxySetToClash() |
| 142 | + |
| 143 | + guard shouldCleanSystemProxy else { return nil } |
| 144 | + return ConfigManager.shared.proxyState.isSystemProxySetByOther |
| 145 | + } |
| 146 | + |
| 147 | + private func prepareForTerminationWait() { |
| 148 | + if let statusItem = AppDelegate.shared.statusItem, statusItem.menu != nil { |
| 149 | + statusItem.menu = nil |
| 150 | + } |
| 151 | + AppDelegate.shared.disposeBag = DisposeBag() |
| 152 | + } |
| 153 | + |
| 154 | + private func performProxyCleanup(forceDisable: Bool, timeout: TimeInterval) async -> Bool { |
| 155 | + await withTaskGroup(of: Bool.self, returning: Bool.self) { group in |
| 156 | + group.addTask { |
| 157 | + await SystemProxyManager.shared.disableProxy(forceDisable: forceDisable) |
| 158 | + return true |
| 159 | + } |
| 160 | + group.addTask { |
| 161 | + try? await Task.sleep(seconds: timeout) |
| 162 | + return false |
| 163 | + } |
| 164 | + let result = await group.next() ?? false |
| 165 | + group.cancelAll() |
| 166 | + return result |
| 167 | + } |
| 168 | + } |
| 169 | +} |
0 commit comments