punchnet-macos/punchnet/App/AppWindow.swift
2026-05-26 19:38:47 +08:00

63 lines
1.4 KiB
Swift

//
// AppWindow.swift
// punchnet
//
// Created by Codex on 2026/5/26.
//
import AppKit
import SwiftUI
enum AppWindow {
static let main = "main"
static let settings = "settings"
@MainActor
static func open(id: String, using openWindow: OpenWindowAction) {
openWindow(id: id)
bringToFront(id: id)
}
@MainActor
static func bringToFront(id: String, attempt: Int = 0) {
NSApp.activate(ignoringOtherApps: true)
if let window = NSApp.windows.first(where: { $0.identifier?.rawValue == id }) {
window.deminiaturize(nil)
window.makeKeyAndOrderFront(nil)
window.orderFrontRegardless()
return
}
guard attempt < 6 else {
return
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
Task { @MainActor in
bringToFront(id: id, attempt: attempt + 1)
}
}
}
}
struct AppWindowIdentifier: NSViewRepresentable {
let id: String
func makeNSView(context: Context) -> NSView {
let view = NSView(frame: .zero)
configure(view)
return view
}
func updateNSView(_ nsView: NSView, context: Context) {
configure(nsView)
}
private func configure(_ view: NSView) {
DispatchQueue.main.async {
view.window?.identifier = NSUserInterfaceItemIdentifier(self.id)
}
}
}