chore(menuitem): improve menuitem refresh logic

This commit is contained in:
yicheng 2020-02-22 11:46:49 +08:00
parent 1e556a2e43
commit ee04d9a826
2 changed files with 18 additions and 9 deletions

View File

@ -157,7 +157,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
self.proxyModeMenuItem.title = "\(NSLocalizedString("Proxy Mode", comment: "")) (\(config.mode.name))"
self.updateProxyList()
MenuItemFactory.refreshMenuItems()
if old?.port != config.port && ConfigManager.shared.proxyPortAutoSet {
SystemProxyManager.shared.enableProxy(port: config.port, socksPort: config.socketPort)
@ -179,9 +179,8 @@ class AppDelegate: NSObject, NSApplicationDelegate {
.isRunningVariable
.asObservable()
.distinctUntilChanged()
.bind { [weak self] _ in
guard let self = self else { return }
self.updateProxyList()
.bind { _ in
MenuItemFactory.refreshMenuItems()
}.disposed(by: disposeBag)
LaunchAtLogin.shared
@ -242,7 +241,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
func updateProxyList() {
if ConfigManager.shared.isRunning {
MenuItemFactory.menuItems { [weak self] items in
MenuItemFactory.refreshMenuItems { [weak self] items in
self?.updateProxyList(withMenus: items)
}
} else {
@ -675,8 +674,9 @@ extension AppDelegate {
extension AppDelegate: NSMenuDelegate {
func menuNeedsUpdate(_ menu: NSMenu) {
syncConfig()
updateProxyList()
updateConfigFiles()
syncConfig()
}
}

View File

@ -11,11 +11,16 @@ import RxCocoa
import SwiftyJSON
class MenuItemFactory {
static func menuItems(completionHandler: @escaping (([NSMenuItem]) -> Void)) {
private static var cachedProxyMenuItem: [NSMenuItem]?
static func refreshMenuItems(completionHandler: (([NSMenuItem]) -> Void)? = nil) {
if ConfigManager.shared.currentConfig?.mode == .direct {
completionHandler([])
completionHandler?([])
return
}
if let cached = cachedProxyMenuItem {
completionHandler?(cached)
}
ApiRequest.requestProxyProviderList {
proxyprovider in
@ -40,7 +45,9 @@ class MenuItemFactory {
menu.isEnabled = true
}
}
completionHandler(menuItems.reversed())
let items = Array(menuItems.reversed())
cachedProxyMenuItem = items
completionHandler?(items)
}
}
}
@ -186,6 +193,8 @@ extension MenuItemFactory {
ConfigManager.selectedProxyRecords.append(newModel)
// terminal Connections for this group
ConnectionManager.closeConnection(for: proxyGroup)
// refresh menu items
MenuItemFactory.refreshMenuItems()
}
}
}