123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- //
- // 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
- // }
-
- // 确保在主线程上执行
- guard Thread.isMainThread else {
- var resp: NSApplication.ModalResponse = .abort
- DispatchQueue.main.sync {
- resp = _runModelForMainThread(style: style, message: message, informative: informative, buttons: buttons)
- }
- return resp
- }
-
- // 参数有效性检查
- // guard !buttons.isEmpty else {
- // assertionFailure("Buttons array should not be empty")
- // return .abort
- // }
-
- let alert = NSAlert()
- alert.alertStyle = style
- alert.messageText = message
- alert.informativeText = informative
-
- for title in buttons {
- alert.addButton(withTitle: title)
- }
- return alert.runModal()
- }
- }
|