// // KMAlertTool.swift // PDF Reader Pro // // Created by tangchao on 2023/12/7. // import Cocoa class KMAlertTool: NSObject { /* * NSAlert 弹窗封装 * 主线程执行 */ public class func runModel(style: NSAlert.Style = .critical, message: String, informative: String = "", buttons: [String] = [], callback: @escaping ((NSApplication.ModalResponse)->Void)) { let block = { let result = Self._runModelForMainThread(style: style, message: message, informative: informative, buttons: buttons) callback(result) } if Thread.isMainThread { block() } else { Task { @MainActor in block() } } } /* * NSAlert 弹窗封装 * 主线程执行 * 异步函数 */ @available(macOS 10.15.0, iOS 13.0, *) public class func runModel(style: NSAlert.Style = .critical, message: String, informative: String = "", buttons: [String] = []) async -> NSApplication.ModalResponse { return await withCheckedContinuation({ continuation in self.runModel(style: style, message: message, informative: informative, buttons: buttons) { response in continuation.resume(returning: response) } }) } /* * NSAlert 弹窗封装 * 主线程调用 * 无返回值 */ public class func runModelForMainThread(style: NSAlert.Style = .critical, message: String, informative: String = "", buttons: [String] = []) { _ = self._runModelForMainThread(style: style, message: message, informative: informative, buttons: buttons) } /* * NSAlert 弹窗封装 * 主线程调用 * 有返回值 */ public class func runModelForMainThread_r(style: NSAlert.Style = .critical, message: String, informative: String = "", buttons: [String] = []) -> NSApplication.ModalResponse { return self._runModelForMainThread(style: style, message: message, informative: informative, buttons: buttons) } // MARK: - Private Methods /* * NSAlert 弹窗封装 * 主线程调用 */ private class func _runModelForMainThread(style: NSAlert.Style = .critical, message: String, informative: String = "", buttons: [String] = []) -> NSApplication.ModalResponse { if Thread.isMainThread == false { #if DEBUG assert(false, "need main thread doing ...") #endif return .stop } let alert = NSAlert() alert.alertStyle = style alert.messageText = message alert.informativeText = informative for title in buttons { alert.addButton(withTitle: title) } return alert.runModal() } }