118 lines
3.1 KiB
Swift
118 lines
3.1 KiB
Swift
//
|
|
// sdlanApp.swift
|
|
// sdlan
|
|
//
|
|
// Created by 安礼成 on 2024/1/17.
|
|
//
|
|
|
|
import SwiftUI
|
|
import AppKit
|
|
import SwiftData
|
|
import Combine
|
|
|
|
@main
|
|
struct sdlanApp: App {
|
|
/*
|
|
var sharedModelContainer: ModelContainer = {
|
|
let schema = Schema([
|
|
Item.self,
|
|
])
|
|
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
|
|
|
|
do {
|
|
return try ModelContainer(for: schema, configurations: [modelConfiguration])
|
|
} catch {
|
|
fatalError("Could not create ModelContainer: \(error)")
|
|
}
|
|
}()
|
|
*/
|
|
|
|
@Environment(\.openWindow) private var openWindow
|
|
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
|
|
|
|
@AppStorage("token") var token: String = ""
|
|
@ObservedObject var vpnManager = VPNManager.shared
|
|
|
|
var body: some Scene {
|
|
WindowGroup(id: "mainWindow") {
|
|
ContentView()
|
|
}
|
|
.commands {
|
|
CommandGroup(replacing: .appInfo) {
|
|
Button {
|
|
openWindow(id: "abortSDLAN")
|
|
} label: {
|
|
Text("About sdlan")
|
|
}
|
|
}
|
|
}
|
|
|
|
Window("", id: "abortSDLAN") {
|
|
AbortView()
|
|
}
|
|
|
|
//.modelContainer(sharedModelContainer)
|
|
MenuBarExtra("sdlanApp", systemImage: "hammer") {
|
|
VStack {
|
|
Button(action: {
|
|
self.menuClick()
|
|
}, label: {
|
|
Text(vpnManager.title)
|
|
})
|
|
|
|
Divider()
|
|
|
|
Button(action: {
|
|
NSApplication.shared.terminate(nil)
|
|
}, label: { Text("退出") })
|
|
|
|
}
|
|
}
|
|
.menuBarExtraStyle(.menu)
|
|
}
|
|
|
|
private func menuClick() {
|
|
switch self.vpnManager.vpnStatus {
|
|
case .disconnected:
|
|
if token.isEmpty {
|
|
let windows = NSApplication.shared.windows
|
|
if let window = windows.first(where: {$0.title == "sdlan"}) {
|
|
window.level = .floating
|
|
} else {
|
|
self.openWindow(id: "mainWindow")
|
|
}
|
|
} else {
|
|
Task {
|
|
try await vpnManager.enableVpn(options: ["token": token as NSObject])
|
|
}
|
|
}
|
|
case .connected:
|
|
Task {
|
|
try await vpnManager.disableVpn()
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
// 处理APP的生命周期
|
|
class AppDelegate: NSObject, NSApplicationDelegate {
|
|
|
|
func applicationWillFinishLaunching(_ notification: Notification) {
|
|
UDPNoticeCenterServer.shared.start()
|
|
}
|
|
|
|
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
|
|
Task {
|
|
try await VPNManager.shared.disableVpn()
|
|
DispatchQueue.main.async {
|
|
sender.reply(toApplicationShouldTerminate: true)
|
|
}
|
|
UDPNoticeCenterServer.shared.stop()
|
|
}
|
|
|
|
return .terminateLater
|
|
}
|
|
|
|
}
|