Skip to content

Commit 35beb3c

Browse files
committed
fix(macOS): stop network extension before quitting
1 parent 2f2b72d commit 35beb3c

2 files changed

Lines changed: 43 additions & 1 deletion

File tree

EasyTier/EasyTierApp.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,29 @@ import AppKit
66

77
@MainActor
88
private final class EasyTierAppDelegate: NSObject, NSApplicationDelegate {
9+
var terminationHandler: (() async -> Void)?
10+
11+
private var terminationTask: Task<Void, Never>?
12+
913
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
1014
sender.setActivationPolicy(.accessory)
1115
return false
1216
}
17+
18+
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
19+
guard let terminationHandler else {
20+
return .terminateNow
21+
}
22+
guard terminationTask == nil else {
23+
return .terminateLater
24+
}
25+
26+
terminationTask = Task { @MainActor in
27+
await terminationHandler()
28+
sender.reply(toApplicationShouldTerminate: true)
29+
}
30+
return .terminateLater
31+
}
1332
}
1433
#endif
1534

@@ -51,6 +70,9 @@ struct EasyTierApp: App {
5170
#if os(macOS)
5271
Window("EasyTier", id: "main") {
5372
ContentView(manager: manager)
73+
.onAppear {
74+
configureTerminationHandler()
75+
}
5476
}
5577

5678
MenuBarExtra(
@@ -59,6 +81,9 @@ struct EasyTierApp: App {
5981
isInserted: $isMenuBarInserted
6082
) {
6183
MenuBarView(manager: manager)
84+
.onAppear {
85+
configureTerminationHandler()
86+
}
6287
}
6388
.menuBarExtraStyle(.window)
6489
#else
@@ -67,4 +92,12 @@ struct EasyTierApp: App {
6792
}
6893
#endif
6994
}
95+
96+
#if os(macOS)
97+
private func configureTerminationHandler() {
98+
appDelegate.terminationHandler = {
99+
await manager.disconnect()
100+
}
101+
}
102+
#endif
70103
}

EasyTier/Utils/NetworkExtensionManager.swift

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,9 +262,18 @@ class NetworkExtensionManager: NetworkExtensionManagerProtocol {
262262
Self.logger.error("disconnect() failed: manager is nil")
263263
return
264264
}
265-
manager.connection.stopVPNTunnel()
265+
let connection = manager.connection
266+
guard [.connecting, .connected, .reasserting, .disconnecting].contains(connection.status) else {
267+
return
268+
}
269+
270+
connection.stopVPNTunnel()
266271
// Immediately sync widget state after initiating disconnection
267272
syncWidgetState()
273+
274+
while [.connecting, .connected, .reasserting, .disconnecting].contains(connection.status) {
275+
try? await Task.sleep(for: .milliseconds(100))
276+
}
268277
}
269278

270279
func updateName(name: String, server: String) async {

0 commit comments

Comments
 (0)