ClashX.Meta/ClashX/AppDelegate.swift

992 lines
37 KiB
Swift
Raw Normal View History

2018-06-13 10:44:30 +08:00
//
// AppDelegate.swift
// ClashX
//
2018-08-08 13:47:38 +08:00
// Created by CYC on 2018/6/10.
// Copyright © 2018 yichengchen. All rights reserved.
2018-06-13 10:44:30 +08:00
//
2019-10-20 13:40:50 +08:00
import Alamofire
2018-06-13 10:44:30 +08:00
import Cocoa
2023-09-05 10:07:46 +08:00
import CocoaLumberjack
import LetsMove
2018-08-04 14:33:47 +08:00
import RxCocoa
import RxSwift
2020-03-13 18:17:34 +08:00
import AppCenter
import AppCenterAnalytics
import AppCenterCrashes
2023-03-01 11:43:48 +08:00
let statusItemLengthWithSpeed: CGFloat = 72
2023-09-05 10:07:46 +08:00
@main
2018-06-13 10:44:30 +08:00
class AppDelegate: NSObject, NSApplicationDelegate {
var statusItem: NSStatusItem!
2023-09-05 10:07:46 +08:00
@IBOutlet var checkForUpdateMenuItem: NSMenuItem!
2023-06-15 14:24:00 +08:00
2019-10-20 13:40:50 +08:00
@IBOutlet var statusMenu: NSMenu!
@IBOutlet var proxySettingMenuItem: NSMenuItem!
@IBOutlet var autoStartMenuItem: NSMenuItem!
@IBOutlet var proxyModeGlobalMenuItem: NSMenuItem!
@IBOutlet var proxyModeDirectMenuItem: NSMenuItem!
@IBOutlet var proxyModeRuleMenuItem: NSMenuItem!
@IBOutlet var allowFromLanMenuItem: NSMenuItem!
@IBOutlet var proxyModeMenuItem: NSMenuItem!
@IBOutlet var showNetSpeedIndicatorMenuItem: NSMenuItem!
@IBOutlet var dashboardMenuItem: NSMenuItem!
@IBOutlet var separatorLineTop: NSMenuItem!
@IBOutlet var sepatatorLineEndProxySelect: NSMenuItem!
@IBOutlet var configSeparatorLine: NSMenuItem!
@IBOutlet var logLevelMenuItem: NSMenuItem!
@IBOutlet var httpPortMenuItem: NSMenuItem!
@IBOutlet var socksPortMenuItem: NSMenuItem!
@IBOutlet var apiPortMenuItem: NSMenuItem!
2019-11-30 19:29:57 +08:00
@IBOutlet var ipMenuItem: NSMenuItem!
2019-10-20 13:40:50 +08:00
@IBOutlet var remoteConfigAutoupdateMenuItem: NSMenuItem!
@IBOutlet var copyExportCommandMenuItem: NSMenuItem!
@IBOutlet var copyExportCommandExternalMenuItem: NSMenuItem!
2020-07-10 20:59:00 +08:00
@IBOutlet var externalControlSeparator: NSMenuItem!
2023-07-16 12:16:15 +08:00
@IBOutlet var connectionsMenuItem: NSMenuItem!
2020-07-10 20:59:00 +08:00
var disposeBag = DisposeBag()
2023-03-01 11:43:48 +08:00
var statusItemView: StatusItemViewProtocol!
2019-02-19 09:45:23 +08:00
var isSpeedTesting = false
2019-10-20 13:40:50 +08:00
2020-05-10 12:17:51 +08:00
var runAfterConfigReload: (() -> Void)?
2020-04-07 23:58:30 +08:00
func applicationWillFinishLaunching(_ notification: Notification) {
Logger.log("applicationWillFinishLaunching")
signal(SIGPIPE, SIG_IGN)
// crash recorder
2020-04-07 23:58:30 +08:00
failLaunchProtect()
NSAppleEventManager.shared()
.setEventHandler(self,
andSelector: #selector(handleURL(event:reply:)),
forEventClass: AEEventClass(kInternetEventClass),
andEventID: AEEventID(kAEGetURL))
2020-04-07 23:58:30 +08:00
}
2019-10-20 13:40:50 +08:00
2020-04-07 23:58:30 +08:00
func applicationDidFinishLaunching(_ notification: Notification) {
Logger.log("applicationDidFinishLaunching")
Logger.log("Appversion: \(AppVersionUtil.currentVersion) \(AppVersionUtil.currentBuild)")
ProcessInfo.processInfo.disableSuddenTermination()
2018-12-09 00:06:43 +08:00
// setup menu item first
2019-10-20 13:40:50 +08:00
statusItem = NSStatusBar.system.statusItem(withLength: statusItemLengthWithSpeed)
2023-09-05 09:30:03 +08:00
statusItemView = StatusItemView.create(statusItem: statusItem)
2023-03-01 11:43:48 +08:00
statusItemView.updateSize(width: statusItemLengthWithSpeed)
2018-12-09 00:06:43 +08:00
statusMenu.delegate = self
2023-09-05 18:53:18 +08:00
setupStatusMenuItemData()
2020-04-07 23:58:30 +08:00
DispatchQueue.main.async {
self.postFinishLaunching()
}
}
2019-10-20 13:40:50 +08:00
2020-04-07 23:58:30 +08:00
func postFinishLaunching() {
Logger.log("postFinishLaunching")
2020-04-07 23:58:30 +08:00
defer {
statusItem.menu = statusMenu
DispatchQueue.main.asyncAfter(deadline: .now() + 8) {
self.checkMenuIconVisable()
}
2020-04-07 23:58:30 +08:00
}
if #unavailable(macOS 10.15) {
// dashboard is not support in macOS 10.15 below
self.dashboardMenuItem.isHidden = true
2023-07-16 12:16:15 +08:00
self.connectionsMenuItem.isHidden = true
}
AppVersionUtil.showUpgradeAlert()
ICloudManager.shared.setup()
2023-07-12 14:39:53 +08:00
if WebPortalManager.hasWebProtal {
WebPortalManager.shared.addWebProtalMenuItem(&statusMenu)
}
AutoUpgardeManager.shared.setup()
AutoUpgardeManager.shared.setupCheckForUpdatesMenuItem(checkForUpdateMenuItem)
// install proxy helper
_ = ClashResourceManager.check()
2020-04-21 23:57:06 +08:00
PrivilegedHelperManager.shared.checkInstall()
2018-12-09 22:00:15 +08:00
ConfigFileManager.copySampleConfigIfNeed()
2019-10-20 13:40:50 +08:00
2018-10-14 23:42:53 +08:00
PFMoveToApplicationsFolderIfNecessary()
2019-11-02 11:55:18 +08:00
// claer not existed selected model
removeUnExistProxyGroups()
2019-10-20 13:40:50 +08:00
// clash logger
if ApiRequest.useDirectApi() {
Logger.log("setup built in logger/traffic")
clash_setLogBlock { line, level in
let clashLevel = ClashLogLevel(rawValue: level ?? "info")
Logger.log(line ?? "", level: clashLevel ?? .info, function: "")
}
clashSetupLogger()
clash_setTrafficBlock { [weak self] up, down in
if RemoteControlManager.selectConfig == nil {
DispatchQueue.main.async {
self?.didUpdateTraffic(up: Int(up), down: Int(down))
}
}
}
clashSetupTraffic()
} else {
Logger.log("do not setup built in logger/traffic, useDirectApi = false")
}
2018-12-09 00:06:43 +08:00
// start proxy
Logger.log("initClashCore")
2020-04-20 10:53:48 +08:00
initClashCore()
Logger.log("initClashCore finish")
2020-03-04 18:30:53 +08:00
setupData()
2020-05-10 12:17:51 +08:00
runAfterConfigReload = { [weak self] in
2023-07-12 14:39:53 +08:00
if !Settings.builtInApiMode {
self?.selectAllowLanWithMenory()
}
2020-05-10 12:17:51 +08:00
}
2020-03-05 09:26:06 +08:00
updateConfig(showNotification: false)
updateLoggingLevel()
2019-10-20 13:40:50 +08:00
// start watch config file change
2020-06-02 19:05:32 +08:00
ConfigManager.watchCurrentConfigFile()
2019-10-20 13:40:50 +08:00
RemoteConfigManager.shared.autoUpdateCheck()
2019-10-20 13:40:50 +08:00
2019-10-15 22:40:02 +08:00
setupNetworkNotifier()
registCrashLogger()
2023-05-26 15:45:33 +08:00
KeyboardShortCutManager.setup()
2023-07-16 12:16:15 +08:00
RemoteControlManager.setupMenuItem(separator: externalControlSeparator)
2018-06-13 10:44:30 +08:00
}
2019-10-20 13:40:50 +08:00
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
let group = DispatchGroup()
var shouldWait = false
2020-10-24 19:54:01 +08:00
if ConfigManager.shared.proxyPortAutoSet && !ConfigManager.shared.isProxySetByOtherVariable.value || NetworkChangeNotifier.isCurrentSystemSetToClash(looser: true) ||
NetworkChangeNotifier.hasInterfaceProxySetToClash() {
Logger.log("ClashX quit need clean proxy setting")
shouldWait = true
group.enter()
SystemProxyManager.shared.disableProxy(forceDisable: ConfigManager.shared.isProxySetByOtherVariable.value) {
group.leave()
}
}
if !shouldWait {
Logger.log("ClashX quit without clean waiting")
return .terminateNow
}
if statusItem != nil, statusItem.menu != nil {
statusItem.menu = nil
}
disposeBag = DisposeBag()
DispatchQueue.global(qos: .default).async {
let res = group.wait(timeout: .now() + 5)
switch res {
case .success:
Logger.log("ClashX quit after clean up finish")
2023-09-05 10:07:46 +08:00
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
2020-10-24 19:54:01 +08:00
NSApp.reply(toApplicationShouldTerminate: true)
}
2023-09-05 10:07:46 +08:00
DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
2020-12-06 14:02:45 +08:00
NSApp.reply(toApplicationShouldTerminate: true)
}
case .timedOut:
Logger.log("ClashX quit after clean up timeout")
2020-10-24 19:54:01 +08:00
DispatchQueue.main.async {
NSApp.reply(toApplicationShouldTerminate: true)
}
2023-09-05 10:07:46 +08:00
DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
2020-12-06 14:02:45 +08:00
NSApp.reply(toApplicationShouldTerminate: true)
}
}
2018-06-13 10:44:30 +08:00
}
Logger.log("ClashX quit wait for clean up")
return .terminateLater
}
func applicationWillTerminate(_ aNotification: Notification) {
2019-11-09 11:50:51 +08:00
UserDefaults.standard.set(0, forKey: "launch_fail_times")
2020-10-24 19:54:01 +08:00
Logger.log("ClashX will terminate")
if NetworkChangeNotifier.isCurrentSystemSetToClash(looser: true) ||
NetworkChangeNotifier.hasInterfaceProxySetToClash() {
Logger.log("Need Reset Proxy Setting again", level: .error)
2020-10-24 19:54:01 +08:00
SystemProxyManager.shared.disableProxy()
}
2018-06-13 10:44:30 +08:00
}
2023-02-20 09:09:22 +08:00
func checkMenuIconVisable() {
2023-09-05 10:07:46 +08:00
guard let button = statusItem.button else { assertionFailure(); return }
guard let window = button.window else { assertionFailure(); return }
let buttonRect = button.convert(button.bounds, to: nil)
let onScreenRect = window.convertToScreen(buttonRect)
var leftScreenX: CGFloat = 0
2023-06-14 11:17:27 +08:00
for screen in NSScreen.screens where screen.frame.origin.x < leftScreenX {
leftScreenX = screen.frame.origin.x
}
let isMenuIconHidden = onScreenRect.midX < leftScreenX
2023-02-20 09:09:22 +08:00
var isCoverdByNotch = false
if #available(macOS 12, *), NSScreen.screens.count == 1, let screen = NSScreen.screens.first, let leftArea = screen.auxiliaryTopLeftArea, let rightArea = screen.auxiliaryTopRightArea {
2023-09-05 10:07:46 +08:00
if onScreenRect.minX > leftArea.maxX, onScreenRect.maxX < rightArea.minX {
isCoverdByNotch = true
}
}
2023-02-20 09:09:22 +08:00
Logger.log("checkMenuIconVisable: \(onScreenRect) \(leftScreenX), hidden: \(isMenuIconHidden), coverd by notch:\(isCoverdByNotch)")
2023-09-05 10:07:46 +08:00
if isMenuIconHidden || isCoverdByNotch, !Settings.disableMenubarNotice {
let alert = NSAlert()
alert.messageText = NSLocalizedString("The status icon is coverd or hide by other app.", comment: "")
alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
alert.addButton(withTitle: NSLocalizedString("Never show again", comment: ""))
if alert.runModal() == .alertSecondButtonReturn {
Settings.disableMenubarNotice = true
}
}
}
2019-10-20 13:40:50 +08:00
2020-04-07 23:58:30 +08:00
func setupStatusMenuItemData() {
ConfigManager.shared
.showNetSpeedIndicatorObservable
2019-10-20 13:40:50 +08:00
.bind { [weak self] show in
guard let self = self else { return }
self.showNetSpeedIndicatorMenuItem.state = (show ?? true) ? .on : .off
2019-10-20 13:40:50 +08:00
let statusItemLength: CGFloat = (show ?? true) ? statusItemLengthWithSpeed : 25
self.statusItem.length = statusItemLength
2023-03-01 11:43:48 +08:00
self.statusItemView.updateSize(width: statusItemLength)
2019-10-20 13:40:50 +08:00
self.statusItemView.showSpeedContainer(show: show ?? true)
}.disposed(by: disposeBag)
2020-04-07 23:58:30 +08:00
statusItemView.updateViewStatus(enableProxy: ConfigManager.shared.proxyPortAutoSet)
}
func setupData() {
2023-05-24 11:07:26 +08:00
SSIDSuspendTool.shared.setup()
ConfigManager.shared
.showNetSpeedIndicatorObservable.skip(1)
.bind {
_ in
ApiRequest.shared.resetTrafficStreamApi()
2020-04-11 11:30:48 +08:00
}.disposed(by: disposeBag)
2019-10-15 22:40:02 +08:00
Observable
.merge([ConfigManager.shared.proxyPortAutoSetObservable,
2023-05-24 11:07:26 +08:00
ConfigManager.shared.isProxySetByOtherVariable.asObservable(),
ConfigManager.shared.proxyShouldPaused.asObservable()])
.observe(on: MainScheduler.instance)
2019-10-15 22:40:02 +08:00
.map { _ -> NSControl.StateValue in
2023-09-05 10:07:46 +08:00
if (ConfigManager.shared.isProxySetByOtherVariable.value || ConfigManager.shared.proxyShouldPaused.value) && ConfigManager.shared.proxyPortAutoSet {
2019-10-15 22:40:02 +08:00
return .mixed
}
return ConfigManager.shared.proxyPortAutoSet ? .on : .off
2019-10-20 13:40:50 +08:00
}.distinctUntilChanged()
2019-10-15 22:40:02 +08:00
.bind { [weak self] status in
2019-10-20 13:40:50 +08:00
guard let self = self else { return }
2019-10-15 22:40:02 +08:00
self.proxySettingMenuItem.state = status
self.statusItemView.updateViewStatus(enableProxy: status == .on)
2019-10-20 13:40:50 +08:00
}.disposed(by: disposeBag)
let configObservable = ConfigManager.shared
.currentConfigVariable
.asObservable()
2019-10-20 13:40:50 +08:00
Observable.zip(configObservable, configObservable.skip(1))
.filter { _, new in return new != nil }
.observe(on: MainScheduler.instance)
2019-10-20 13:40:50 +08:00
.bind { [weak self] old, config in
guard let self = self, let config = config else { return }
self.proxyModeDirectMenuItem.state = .off
self.proxyModeGlobalMenuItem.state = .off
self.proxyModeRuleMenuItem.state = .off
2019-10-20 13:40:50 +08:00
switch config.mode {
2019-10-20 13:40:50 +08:00
case .direct: self.proxyModeDirectMenuItem.state = .on
case .global: self.proxyModeGlobalMenuItem.state = .on
case .rule: self.proxyModeRuleMenuItem.state = .on
}
self.allowFromLanMenuItem.state = config.allowLan ? .on : .off
2019-10-20 13:40:50 +08:00
2019-07-28 12:39:49 +08:00
self.proxyModeMenuItem.title = "\(NSLocalizedString("Proxy Mode", comment: "")) (\(config.mode.name))"
2019-10-20 13:40:50 +08:00
2020-06-16 14:30:32 +08:00
if old?.usedHttpPort != config.usedHttpPort || old?.usedSocksPort != config.usedSocksPort {
Logger.log("port config updated,new: \(config.usedHttpPort),\(config.usedSocksPort)")
2020-05-10 12:17:51 +08:00
if ConfigManager.shared.proxyPortAutoSet {
2020-06-16 14:30:32 +08:00
SystemProxyManager.shared.enableProxy(port: config.usedHttpPort, socksPort: config.usedSocksPort)
2020-05-10 12:17:51 +08:00
}
}
2019-10-20 13:40:50 +08:00
2020-06-16 14:30:32 +08:00
self.httpPortMenuItem.title = "Http Port: \(config.usedHttpPort)"
self.socksPortMenuItem.title = "Socks Port: \(config.usedSocksPort)"
2019-11-30 19:29:57 +08:00
self.apiPortMenuItem.title = "Api Port: \(ConfigManager.shared.apiPort)"
self.ipMenuItem.title = "IP: \(NetworkChangeNotifier.getPrimaryIPAddress() ?? "")"
if RemoteControlManager.selectConfig == nil {
ClashStatusTool.checkPortConfig(cfg: config)
}
2019-10-20 13:40:50 +08:00
}.disposed(by: disposeBag)
2020-12-17 09:25:13 +08:00
if !PrivilegedHelperManager.shared.isHelperCheckFinished.value &&
ConfigManager.shared.proxyPortAutoSet {
PrivilegedHelperManager.shared.isHelperCheckFinished
2023-09-05 10:07:46 +08:00
.filter { $0 }
2020-12-17 09:25:13 +08:00
.take(1)
2023-09-05 10:07:46 +08:00
.take(while: { _ in ConfigManager.shared.proxyPortAutoSet })
.observe(on: MainScheduler.instance)
.bind(onNext: { _ in
2020-12-17 09:25:13 +08:00
SystemProxyManager.shared.enableProxy()
}).disposed(by: disposeBag)
} else if ConfigManager.shared.proxyPortAutoSet {
SystemProxyManager.shared.enableProxy()
2020-12-17 09:25:13 +08:00
}
2023-09-05 18:53:18 +08:00
LaunchAtLogin.shared
.isEnableVirable
.asObservable()
.subscribe(onNext: { [weak self] enable in
guard let self = self else { return }
self.autoStartMenuItem.state = enable ? .on : .off
}).disposed(by: disposeBag)
remoteConfigAutoupdateMenuItem.state = RemoteConfigManager.autoUpdateEnable ? .on : .off
2020-12-17 09:25:13 +08:00
if !PrivilegedHelperManager.shared.isHelperCheckFinished.value {
proxySettingMenuItem.target = nil
PrivilegedHelperManager.shared.isHelperCheckFinished
2023-09-05 10:07:46 +08:00
.filter { $0 }
2020-12-17 09:25:13 +08:00
.take(1)
.observe(on: MainScheduler.instance)
2020-12-17 09:25:13 +08:00
.subscribe { [weak self] _ in
guard let self = self else { return }
self.proxySettingMenuItem.target = self
}.disposed(by: disposeBag)
}
2019-10-15 22:40:02 +08:00
}
2019-10-20 13:40:50 +08:00
2019-10-15 22:40:02 +08:00
func setupNetworkNotifier() {
2021-06-15 20:07:21 +08:00
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
NetworkChangeNotifier.start()
}
2019-10-20 13:40:50 +08:00
2019-10-15 22:40:02 +08:00
NotificationCenter
.default
.rx
.notification(.systemNetworkStatusDidChange)
.observe(on: MainScheduler.instance)
2019-12-10 17:19:07 +08:00
.delay(.milliseconds(200), scheduler: MainScheduler.instance)
2019-10-20 13:40:50 +08:00
.bind { _ in
guard NetworkChangeNotifier.getPrimaryInterface() != nil else { return }
let proxySetted = NetworkChangeNotifier.isCurrentSystemSetToClash()
2019-10-15 22:40:02 +08:00
ConfigManager.shared.isProxySetByOtherVariable.accept(!proxySetted)
if !proxySetted && ConfigManager.shared.proxyPortAutoSet {
let proxiesSetting = NetworkChangeNotifier.getRawProxySetting()
2020-10-24 19:54:01 +08:00
Logger.log("Proxy changed by other process!, current:\(proxiesSetting), is Interface Set: \(NetworkChangeNotifier.hasInterfaceProxySetToClash())", level: .warning)
}
2019-10-20 13:40:50 +08:00
}.disposed(by: disposeBag)
NSWorkspace.shared.notificationCenter.addObserver(
self, selector: #selector(resetProxySettingOnWakeupFromSleep),
name: NSWorkspace.didWakeNotification, object: nil
)
NotificationCenter
.default
.rx
2023-09-05 10:07:46 +08:00
.notification(.systemNetworkStatusIPUpdate).map { _ in
NetworkChangeNotifier.getPrimaryIPAddress(allowIPV6: false)
2023-09-05 10:07:46 +08:00
}
.startWith(NetworkChangeNotifier.getPrimaryIPAddress(allowIPV6: false))
.distinctUntilChanged()
.skip(1)
.filter { $0 != nil }
.observe(on: MainScheduler.instance)
.debounce(.seconds(5), scheduler: MainScheduler.instance).bind { [weak self] _ in
self?.healthCheckOnNetworkChange()
}.disposed(by: disposeBag)
ConfigManager.shared
.isProxySetByOtherVariable
.asObservable()
.filter { _ in ConfigManager.shared.proxyPortAutoSet }
.distinctUntilChanged()
2023-05-24 11:07:26 +08:00
.filter { $0 }
.filter { _ in !ConfigManager.shared.proxyShouldPaused.value }
.bind { _ in
let rawProxy = NetworkChangeNotifier.getRawProxySetting()
Logger.log("proxy changed to no clashX setting: \(rawProxy)", level: .warning)
NSUserNotificationCenter.default.postProxyChangeByOtherAppNotice()
}.disposed(by: disposeBag)
NotificationCenter
.default
.rx
2023-09-05 10:07:46 +08:00
.notification(.systemNetworkStatusIPUpdate).map { _ in
NetworkChangeNotifier.getPrimaryIPAddress(allowIPV6: false)
2023-09-05 10:07:46 +08:00
}.bind { [weak self] _ in
if RemoteControlManager.selectConfig != nil {
self?.resetStreamApi()
}
}.disposed(by: disposeBag)
2018-06-13 10:44:30 +08:00
}
2019-10-20 13:40:50 +08:00
func updateProxyList(withMenus menus: [NSMenuItem]) {
let startIndex = statusMenu.items.firstIndex(of: separatorLineTop)! + 1
let endIndex = statusMenu.items.firstIndex(of: sepatatorLineEndProxySelect)!
2023-07-16 12:16:15 +08:00
sepatatorLineEndProxySelect.isHidden = menus.isEmpty
2023-09-05 10:07:46 +08:00
for _ in 0 ..< endIndex - startIndex {
2019-10-20 00:10:27 +08:00
statusMenu.removeItem(at: startIndex)
2019-03-24 13:59:12 +08:00
}
2019-10-20 00:10:27 +08:00
for each in menus {
statusMenu.insertItem(each, at: startIndex)
2019-03-24 13:59:12 +08:00
}
}
2019-10-20 13:40:50 +08:00
2018-11-30 22:14:20 +08:00
func updateConfigFiles() {
2019-10-20 13:40:50 +08:00
guard let menu = configSeparatorLine.menu else { return }
2020-05-10 23:36:43 +08:00
MenuItemFactory.generateSwitchConfigMenuItems {
items in
let lineIndex = menu.items.firstIndex(of: self.configSeparatorLine)!
2023-09-05 10:07:46 +08:00
for _ in 0 ..< lineIndex {
2020-05-10 23:36:43 +08:00
menu.removeItem(at: 0)
}
for item in items.reversed() {
menu.insertItem(item, at: 0)
}
2019-10-20 00:10:27 +08:00
}
2018-08-04 21:49:32 +08:00
}
2019-10-20 13:40:50 +08:00
2018-08-12 11:29:51 +08:00
func updateLoggingLevel() {
2019-10-20 13:28:40 +08:00
ApiRequest.updateLogLevel(level: ConfigManager.selectLoggingApiLevel)
2019-10-20 13:40:50 +08:00
for item in logLevelMenuItem.submenu?.items ?? [] {
2018-08-12 11:29:51 +08:00
item.state = item.title.lowercased() == ConfigManager.selectLoggingApiLevel.rawValue ? .on : .off
}
NotificationCenter.default.post(name: .reloadDashboard, object: nil)
2018-08-12 11:29:51 +08:00
}
2019-10-20 13:40:50 +08:00
2018-06-13 10:44:30 +08:00
func startProxy() {
2019-10-20 13:40:50 +08:00
if ConfigManager.shared.isRunning { return }
2023-06-14 11:17:27 +08:00
if !Settings.isApiSecretSet {
if #available(macOS 11.0, *), let password = SecCreateSharedWebCredentialPassword() as? String {
Settings.apiSecret = password
} else {
Settings.apiSecret = UUID().uuidString
}
}
2023-06-14 11:17:27 +08:00
2023-07-16 12:16:15 +08:00
if clash_checkSecret().toString().isEmpty || Settings.overrideConfigSecret {
clash_setSecret(Settings.apiSecret.goStringBuffer())
}
2019-10-20 13:40:50 +08:00
2019-10-02 21:43:18 +08:00
struct StartProxyResp: Codable {
let externalController: String
let secret: String
}
2019-10-20 13:40:50 +08:00
2018-12-21 10:18:01 +08:00
// setup ui config first
if let htmlPath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "dashboard") {
let uiPath = URL(fileURLWithPath: htmlPath).deletingLastPathComponent().path
2019-10-02 21:43:18 +08:00
setUIPath(uiPath.goStringBuffer())
2018-12-21 10:18:01 +08:00
}
2019-10-20 13:40:50 +08:00
2023-07-12 14:39:53 +08:00
Logger.log("Trying start proxy, build-in mode: \(Settings.builtInApiMode), allow lan: \(ConfigManager.allowConnectFromLan) custom port: \(Settings.proxyPort)")
2023-02-20 14:00:13 +08:00
var apiAddr = ""
if Settings.apiPort > 0 {
if Settings.apiPortAllowLan {
apiAddr = "0.0.0.0:\(Settings.apiPort)"
} else {
apiAddr = "127.0.0.1:\(Settings.apiPort)"
}
}
2023-07-12 14:39:53 +08:00
let startRes = run(Settings.builtInApiMode.goObject(),
2023-09-05 10:07:46 +08:00
ConfigManager.allowConnectFromLan.goObject(),
2023-09-05 16:33:37 +08:00
Settings.enableIPV6.goObject(),
2023-02-20 14:00:13 +08:00
GoUint32(Settings.proxyPort),
2023-09-05 10:07:46 +08:00
apiAddr.goStringBuffer())?
2023-02-20 14:00:13 +08:00
.toString() ?? ""
let jsonData = startRes.data(using: .utf8) ?? Data()
2019-10-20 13:40:50 +08:00
if let res = try? JSONDecoder().decode(StartProxyResp.self, from: jsonData) {
2019-10-02 21:43:18 +08:00
let port = res.externalController.components(separatedBy: ":").last ?? "9090"
2023-02-20 14:00:13 +08:00
ConfigManager.shared.allowExternalControl = !res.externalController.contains("127.0.0.1") && !res.externalController.contains("localhost")
2019-10-02 21:43:18 +08:00
ConfigManager.shared.apiPort = port
ConfigManager.shared.apiSecret = res.secret
ConfigManager.shared.isRunning = true
proxyModeMenuItem.isEnabled = true
dashboardMenuItem.isEnabled = true
} else {
ConfigManager.shared.isRunning = false
proxyModeMenuItem.isEnabled = false
2023-02-20 14:00:13 +08:00
Logger.log(startRes, level: .error)
NSUserNotificationCenter.default.postConfigErrorNotice(msg: startRes)
2018-06-13 10:44:30 +08:00
}
Logger.log("Start proxy done")
2018-08-04 14:33:47 +08:00
}
2019-10-20 13:40:50 +08:00
func syncConfig(completeHandler: (() -> Void)? = nil) {
ApiRequest.requestConfig { config in
ConfigManager.shared.currentConfig = config
completeHandler?()
2018-06-23 21:43:33 +08:00
}
}
2019-10-20 13:40:50 +08:00
2018-08-07 15:09:25 +08:00
func resetStreamApi() {
ApiRequest.shared.delegate = self
ApiRequest.shared.resetStreamApis()
2018-06-13 10:44:30 +08:00
}
2019-10-20 13:40:50 +08:00
func updateConfig(configName: String? = nil, showNotification: Bool = true, completeHandler: ((ErrorString?) -> Void)? = nil) {
startProxy()
2019-10-20 13:40:50 +08:00
guard ConfigManager.shared.isRunning else { return }
let config = configName ?? ConfigManager.selectConfigName
2020-02-26 16:10:21 +08:00
ClashProxy.cleanCache()
ApiRequest.requestConfigUpdate(configName: config) {
[weak self] err in
2019-10-20 13:40:50 +08:00
guard let self = self else { return }
defer {
completeHandler?(err)
}
if let error = err {
NSUserNotificationCenter.default
.postNotificationAlert(title: NSLocalizedString("Reload Config Fail", comment: ""),
2023-09-05 10:07:46 +08:00
info: error)
} else {
self.syncConfig()
self.resetStreamApi()
2020-05-10 12:17:51 +08:00
self.runAfterConfigReload?()
self.runAfterConfigReload = nil
if showNotification {
NSUserNotificationCenter.default
.post(title: NSLocalizedString("Reload Config Succeed", comment: ""),
2020-03-31 20:20:20 +08:00
info: NSLocalizedString("Success", comment: ""))
}
if let newConfigName = configName {
ConfigManager.selectConfigName = newConfigName
}
self.selectProxyGroupWithMemory()
self.selectOutBoundModeWithMenory()
MenuItemFactory.recreateProxyMenuItems()
NotificationCenter.default.post(name: .reloadDashboard, object: nil)
}
}
}
2019-10-20 13:40:50 +08:00
@objc func resetProxySettingOnWakeupFromSleep() {
guard !ConfigManager.shared.isProxySetByOtherVariable.value,
2023-09-05 10:07:46 +08:00
ConfigManager.shared.proxyPortAutoSet else { return }
guard NetworkChangeNotifier.getPrimaryInterface() != nil else { return }
if !NetworkChangeNotifier.isCurrentSystemSetToClash() {
let rawProxy = NetworkChangeNotifier.getRawProxySetting()
Logger.log("Resting proxy setting, current:\(rawProxy)", level: .warning)
SystemProxyManager.shared.disableProxy()
SystemProxyManager.shared.enableProxy()
}
if RemoteControlManager.selectConfig != nil {
resetStreamApi()
}
}
@objc func healthCheckOnNetworkChange() {
ApiRequest.getMergedProxyData {
proxyResp in
2023-09-05 10:07:46 +08:00
guard let proxyResp = proxyResp else { return }
var providers = Set<ClashProxyName>()
2023-09-05 10:07:46 +08:00
let groups = proxyResp.proxyGroups.filter(\.type.isAutoGroup)
for group in groups {
group.all?.compactMap {
proxyResp.proxiesMap[$0]?.enclosingProvider?.name
}.forEach {
providers.insert($0)
}
}
for group in groups {
Logger.log("Start auto health check for group \(group.name)")
ApiRequest.healthCheck(proxy: group.name)
}
for provider in providers {
Logger.log("Start auto health check for provider \(provider)")
ApiRequest.healthCheck(proxy: provider)
2021-07-27 22:22:04 +08:00
}
}
}
}
// MARK: Main actions
extension AppDelegate {
2023-05-26 15:45:33 +08:00
@IBAction func actionDashboard(_ sender: NSMenuItem?) {
2023-07-16 12:16:15 +08:00
ClashWindowController<ClashWebViewContoller>.create().showWindow(sender)
}
@IBAction func actionConnections(_ sender: NSMenuItem?) {
if #available(macOS 10.15, *) {
ClashWindowController<DashboardViewController>.create().showWindow(sender)
}
2020-02-05 21:45:11 +08:00
}
@IBAction func actionAllowFromLan(_ sender: NSMenuItem) {
ApiRequest.updateAllowLan(allow: !ConfigManager.allowConnectFromLan) {
[weak self] in
2019-10-20 13:40:50 +08:00
guard let self = self else { return }
self.syncConfig()
ConfigManager.allowConnectFromLan = !ConfigManager.allowConnectFromLan
}
}
2019-10-20 13:40:50 +08:00
@IBAction func actionStartAtLogin(_ sender: NSMenuItem) {
LaunchAtLogin.shared.isEnabled = !LaunchAtLogin.shared.isEnabled
2018-06-13 10:44:30 +08:00
}
2019-10-20 13:40:50 +08:00
@IBAction func actionSwitchProxyMode(_ sender: NSMenuItem) {
2019-10-20 13:40:50 +08:00
let mode: ClashProxyMode
switch sender {
case proxyModeGlobalMenuItem:
mode = .global
case proxyModeDirectMenuItem:
mode = .direct
case proxyModeRuleMenuItem:
mode = .rule
default:
return
}
2023-05-26 15:45:33 +08:00
switchProxyMode(mode: mode)
}
2023-06-14 11:17:27 +08:00
2023-05-26 15:45:33 +08:00
func switchProxyMode(mode: ClashProxyMode) {
let config = ConfigManager.shared.currentConfig?.copy()
config?.mode = mode
ApiRequest.updateOutBoundMode(mode: mode) { _ in
ConfigManager.shared.currentConfig = config
ConfigManager.selectOutBoundMode = mode
MenuItemFactory.recreateProxyMenuItems()
}
}
2019-10-20 13:40:50 +08:00
@IBAction func actionShowNetSpeedIndicator(_ sender: NSMenuItem) {
ConfigManager.shared.showNetSpeedIndicator = !(sender.state == .on)
}
2019-10-20 13:40:50 +08:00
2023-05-26 15:45:33 +08:00
@IBAction func actionSetSystemProxy(_ sender: Any?) {
var canSaveProxy = true
2023-05-24 11:07:26 +08:00
if ConfigManager.shared.proxyPortAutoSet && ConfigManager.shared.proxyShouldPaused.value {
ConfigManager.shared.proxyPortAutoSet = false
} else if ConfigManager.shared.isProxySetByOtherVariable.value {
2019-10-15 22:40:02 +08:00
// should reset proxy to clashx
ConfigManager.shared.isProxySetByOtherVariable.accept(false)
ConfigManager.shared.proxyPortAutoSet = true
// clear then reset.
canSaveProxy = false
SystemProxyManager.shared.disableProxy(port: 0, socksPort: 0, forceDisable: true)
2019-10-15 22:40:02 +08:00
} else {
ConfigManager.shared.proxyPortAutoSet = !ConfigManager.shared.proxyPortAutoSet
}
2019-10-20 13:40:50 +08:00
if ConfigManager.shared.proxyPortAutoSet {
if canSaveProxy {
SystemProxyManager.shared.saveProxy()
}
2020-06-16 14:30:32 +08:00
SystemProxyManager.shared.enableProxy()
2018-06-13 10:44:30 +08:00
} else {
2020-06-16 14:30:32 +08:00
SystemProxyManager.shared.disableProxy()
2018-06-13 10:44:30 +08:00
}
}
2019-10-20 13:40:50 +08:00
2019-12-17 21:04:11 +08:00
@IBAction func actionCopyExportCommand(_ sender: NSMenuItem) {
2018-06-13 10:44:30 +08:00
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
2020-06-16 14:30:32 +08:00
let port = ConfigManager.shared.currentConfig?.usedHttpPort ?? 0
let socksport = ConfigManager.shared.currentConfig?.usedSocksPort ?? 0
let localhost = "127.0.0.1"
2019-12-17 21:04:11 +08:00
let isLocalhostCopy = sender == copyExportCommandMenuItem
let ip = isLocalhostCopy ? localhost :
NetworkChangeNotifier.getPrimaryIPAddress() ?? localhost
2019-11-06 19:25:29 +08:00
pasteboard.setString("export https_proxy=http://\(ip):\(port) http_proxy=http://\(ip):\(port) all_proxy=socks5://\(ip):\(socksport)", forType: .string)
2018-06-13 10:44:30 +08:00
}
2019-10-20 13:40:50 +08:00
2018-09-23 21:37:11 +08:00
@IBAction func actionSpeedTest(_ sender: Any) {
2019-03-01 17:39:17 +08:00
if isSpeedTesting {
NSUserNotificationCenter.default.postSpeedTestingNotice()
return
}
NSUserNotificationCenter.default.postSpeedTestBeginNotice()
2019-10-20 13:40:50 +08:00
2019-02-19 09:45:23 +08:00
isSpeedTesting = true
2019-10-20 13:40:50 +08:00
ApiRequest.getMergedProxyData { [weak self] resp in
let group = DispatchGroup()
for (name, _) in resp?.enclosingProviderResp?.providers ?? [:] {
group.enter()
ApiRequest.healthCheck(proxy: name) {
group.leave()
}
}
for p in resp?.proxiesMap["GLOBAL"]?.all ?? [] {
group.enter()
ApiRequest.getProxyDelay(proxyName: p) { _ in
group.leave()
2019-02-19 09:45:23 +08:00
}
}
group.notify(queue: DispatchQueue.main) {
2019-02-19 09:45:23 +08:00
NSUserNotificationCenter.default.postSpeedTestFinishNotice()
2019-03-01 17:39:17 +08:00
self?.isSpeedTesting = false
}
2019-02-19 09:45:23 +08:00
}
}
2019-10-20 13:40:50 +08:00
@IBAction func actionUpdateExternalResource(_ sender: Any) {
UpdateExternalResourceAction.run()
}
@IBAction func actionQuit(_ sender: Any) {
NSApplication.shared.terminate(self)
}
}
// MARK: Streaming Info
2019-10-20 13:40:50 +08:00
extension AppDelegate: ApiRequestStreamDelegate {
func didUpdateTraffic(up: Int, down: Int) {
2019-11-21 22:39:10 +08:00
statusItemView.updateSpeedLabel(up: up, down: down)
}
2019-10-20 13:40:50 +08:00
func didGetLog(log: String, level: String) {
Logger.log(log, level: ClashLogLevel(rawValue: level) ?? .unknow)
}
}
// MARK: Help actions
2019-10-20 13:40:50 +08:00
extension AppDelegate {
2023-05-26 15:45:33 +08:00
@IBAction func actionShowLog(_ sender: Any?) {
NSWorkspace.shared.openFile(Logger.shared.logFilePath())
}
}
// MARK: Config actions
extension AppDelegate {
2018-06-13 10:44:30 +08:00
@IBAction func openConfigFolder(_ sender: Any) {
2022-11-20 12:08:46 +08:00
if ICloudManager.shared.useiCloud.value {
ICloudManager.shared.getUrl {
url in
if let url = url {
NSWorkspace.shared.open(url)
}
}
} else {
NSWorkspace.shared.openFile(kConfigFolderPath)
}
2018-06-13 10:44:30 +08:00
}
2019-10-20 13:40:50 +08:00
@IBAction func actionUpdateConfig(_ sender: AnyObject) {
updateConfig()
2018-06-13 10:44:30 +08:00
}
2019-10-20 13:40:50 +08:00
2018-08-12 11:29:51 +08:00
@IBAction func actionSetLogLevel(_ sender: NSMenuItem) {
let level = ClashLogLevel(rawValue: sender.title.lowercased()) ?? .unknow
ConfigManager.selectLoggingApiLevel = level
dynamicLogLevel = level.toDDLogLevel()
2018-08-12 11:29:51 +08:00
updateLoggingLevel()
resetStreamApi()
}
2019-10-20 13:40:50 +08:00
@IBAction func actionAutoUpdateRemoteConfig(_ sender: Any) {
RemoteConfigManager.autoUpdateEnable = !RemoteConfigManager.autoUpdateEnable
remoteConfigAutoupdateMenuItem.state = RemoteConfigManager.autoUpdateEnable ? .on : .off
}
2019-10-20 13:40:50 +08:00
@IBAction func actionUpdateRemoteConfig(_ sender: Any) {
RemoteConfigManager.shared.updateCheck(ignoreTimeLimit: true, showNotification: true)
}
@IBAction func actionSetUpdateInterval(_ sender: Any) {
RemoteConfigManager.showAdd()
}
2018-12-09 00:06:43 +08:00
}
// MARK: crash hanlder
2019-10-20 13:40:50 +08:00
2018-12-09 00:06:43 +08:00
extension AppDelegate {
func registCrashLogger() {
#if DEBUG
return
#else
2020-03-13 18:17:34 +08:00
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
2020-11-14 15:06:46 +08:00
AppCenter.start(withAppSecret: "dce6e9a3-b6e3-4fd2-9f2d-35c767a99663", services: [
Analytics.self,
Crashes.self
2020-03-13 18:17:34 +08:00
])
}
#endif
2018-12-09 00:06:43 +08:00
}
2019-10-20 13:40:50 +08:00
func failLaunchProtect() {
#if DEBUG
return
#else
2023-07-20 08:52:28 +08:00
UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions": false])
let x = UserDefaults.standard
2023-09-05 10:07:46 +08:00
var launch_fail_times = 0
if let xx = x.object(forKey: "launch_fail_times") as? Int { launch_fail_times = xx }
launch_fail_times += 1
x.set(launch_fail_times, forKey: "launch_fail_times")
if launch_fail_times > 3 {
//
ConfigFileManager.backupAndRemoveConfigFile()
try? FileManager.default.removeItem(atPath: kConfigFolderPath + "Country.mmdb")
if let domain = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: domain)
UserDefaults.standard.synchronize()
}
NSUserNotificationCenter.default.post(title: "Fail on launch protect", info: "You origin Config has been renamed", notiOnly: false)
}
2023-09-05 10:07:46 +08:00
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + Double(Int64(5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
x.set(0, forKey: "launch_fail_times")
2023-09-05 10:07:46 +08:00
}
#endif
2018-12-09 00:06:43 +08:00
}
2018-06-13 10:44:30 +08:00
}
// MARK: Memory
2019-10-20 13:40:50 +08:00
extension AppDelegate {
2019-10-20 13:40:50 +08:00
func selectProxyGroupWithMemory() {
2019-11-02 00:04:42 +08:00
let copy = [SavedProxyModel](ConfigManager.selectedProxyRecords)
for item in copy {
2019-11-02 11:55:18 +08:00
guard item.config == ConfigManager.selectConfigName else { continue }
2019-12-11 20:27:17 +08:00
Logger.log("Auto selecting \(item.group) \(item.selected)", level: .debug)
ApiRequest.updateProxyGroup(group: item.group, selectProxy: item.selected) { success in
2019-10-20 13:40:50 +08:00
if !success {
2019-11-02 00:04:42 +08:00
ConfigManager.selectedProxyRecords.removeAll { model -> Bool in
2019-12-11 20:27:17 +08:00
return model.key == item.key
}
}
}
}
}
2019-11-02 11:55:18 +08:00
func removeUnExistProxyGroups() {
let action: (([String]) -> Void) = { list in
let unexists = ConfigManager.selectedProxyRecords.filter {
!list.contains($0.config)
}
ConfigManager.selectedProxyRecords.removeAll {
unexists.contains($0)
}
}
2022-11-20 12:08:46 +08:00
if ICloudManager.shared.useiCloud.value {
ICloudManager.shared.getConfigFilesList { list in
action(list)
}
} else {
let list = ConfigManager.getConfigFilesList()
action(list)
}
}
2019-10-20 13:40:50 +08:00
func selectOutBoundModeWithMenory() {
2019-10-20 13:40:50 +08:00
ApiRequest.updateOutBoundMode(mode: ConfigManager.selectOutBoundMode) {
2019-03-24 13:59:12 +08:00
[weak self] _ in
ConnectionManager.closeAllConnection()
2019-03-24 13:59:12 +08:00
self?.syncConfig()
}
}
2019-10-20 13:40:50 +08:00
func selectAllowLanWithMenory() {
2019-10-20 13:40:50 +08:00
ApiRequest.updateAllowLan(allow: ConfigManager.allowConnectFromLan) {
2019-03-24 13:59:12 +08:00
[weak self] in
self?.syncConfig()
}
}
2020-11-14 15:01:28 +08:00
func hasMenuSelected() -> Bool {
if #available(macOS 11, *) {
return statusMenu.items.contains { $0.state == .on }
} else {
return true
}
}
}
// MARK: NSMenuDelegate
2019-10-20 13:40:50 +08:00
2019-09-14 18:05:36 +08:00
extension AppDelegate: NSMenuDelegate {
func menuNeedsUpdate(_ menu: NSMenu) {
MenuItemFactory.refreshExistingMenuItems()
updateConfigFiles()
syncConfig()
2020-11-14 15:01:28 +08:00
NotificationCenter.default.post(name: .proxyMeneViewShowLeftPadding,
object: nil,
userInfo: ["show": hasMenuSelected()])
}
func menu(_ menu: NSMenu, willHighlight item: NSMenuItem?) {
menu.items.forEach {
($0.view as? ProxyGroupMenuHighlightDelegate)?.highlight(item: item)
}
}
func menuDidClose(_ menu: NSMenu) {
menu.items.forEach {
($0.view as? ProxyGroupMenuHighlightDelegate)?.highlight(item: nil)
}
}
2019-09-14 18:05:36 +08:00
}
2019-09-14 18:05:36 +08:00
// MARK: URL Scheme
2019-10-20 13:40:50 +08:00
2019-09-14 18:05:36 +08:00
extension AppDelegate {
@objc func handleURL(event: NSAppleEventDescriptor, reply: NSAppleEventDescriptor) {
guard let url = event.paramDescriptor(forKeyword: keyDirectObject)?.stringValue else {
return
}
2019-10-20 13:40:50 +08:00
2019-09-14 18:05:36 +08:00
guard let components = URLComponents(string: url),
2020-11-14 15:01:28 +08:00
let scheme = components.scheme,
scheme.hasPrefix("clash"),
let host = components.host
2019-10-20 13:40:50 +08:00
else { return }
2019-09-14 18:05:36 +08:00
if host == "install-config" {
guard let url = components.queryItems?.first(where: { item in
item.name == "url"
2019-10-20 13:40:50 +08:00
})?.value else { return }
var userInfo = ["url": url]
2019-09-14 18:05:36 +08:00
if let name = components.queryItems?.first(where: { item in
item.name == "name"
})?.value {
userInfo["name"] = name
}
2019-10-20 13:40:50 +08:00
2019-09-14 18:05:36 +08:00
remoteConfigAutoupdateMenuItem.menu?.performActionForItem(at: 0)
2019-10-20 13:40:50 +08:00
2019-09-14 18:05:36 +08:00
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
NotificationCenter.default.post(name: Notification.Name(rawValue: "didGetUrl"), object: nil, userInfo: userInfo)
}
} else if host == "update-config" {
2023-09-05 10:07:46 +08:00
updateConfig()
2019-09-14 18:05:36 +08:00
}
}
}