From 89b7f193d716bf8843194eb378e48f5acbbae7e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A7=A6=E5=AE=87=E8=88=AA?= Date: Mon, 1 Apr 2019 09:16:47 +0800 Subject: [PATCH] convert to swift5 --- ShadowsocksX-NG/AppDelegate.swift | 66 ++++++++-------- ShadowsocksX-NG/NetWorkMonitor.swift | 12 +-- ShadowsocksX-NG/PingClient.swift | 4 +- .../PreferencesWindowController.swift | 78 ++++++++++--------- .../ProxyPreferencesController.swift | 4 +- ShadowsocksX-NG/ServerProfileManager.swift | 10 +-- ShadowsocksX-NG/StatusItemView.swift | 4 +- ShadowsocksX-NG/Subscribe.swift | 6 +- ShadowsocksX-NG/SubscribeManager.swift | 2 +- .../SubscribePreferenceWindowController.swift | 39 ++++++---- ShadowsocksX-NG/UserRulesController.swift | 37 +++++---- ShadowsocksX-NG/VersionChecker.swift | 2 +- 12 files changed, 137 insertions(+), 127 deletions(-) diff --git a/ShadowsocksX-NG/AppDelegate.swift b/ShadowsocksX-NG/AppDelegate.swift index b8daf1d..2cb10a0 100644 --- a/ShadowsocksX-NG/AppDelegate.swift +++ b/ShadowsocksX-NG/AppDelegate.swift @@ -101,7 +101,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele setUpMenu(defaults.bool(forKey: "enable_showSpeed")) - statusItem = NSStatusBar.system().statusItem(withLength: 20) + statusItem = NSStatusBar.system.statusItem(withLength: 20) let image = NSImage(named: "menu_icon") image?.isTemplate = true statusItem?.image = image @@ -372,7 +372,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele @IBAction func updateSubscribeAtLaunch(_ sender: NSMenuItem) { let defaults = UserDefaults.standard defaults.set(!defaults.bool(forKey: "AutoUpdateSubscribe"), forKey: "AutoUpdateSubscribe") - updateSubscribeAtLaunchMenuItem.state = defaults.bool(forKey: "AutoUpdateSubscribe") ? 1 : 0 + updateSubscribeAtLaunchMenuItem.state = NSControl.StateValue(rawValue: defaults.bool(forKey: "AutoUpdateSubscribe") ? 1 : 0) } @@ -501,16 +501,16 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele } @IBAction func showLogs(_ sender: NSMenuItem) { - let ws = NSWorkspace.shared() + let ws = NSWorkspace.shared if let appUrl = ws.urlForApplication(withBundleIdentifier: "com.apple.Console") { try! ws.launchApplication(at: appUrl ,options: .default - ,configuration: [NSWorkspaceLaunchConfigurationArguments: "~/Library/Logs/ss-local.log"]) + ,configuration: [NSWorkspace.LaunchConfigurationKey.arguments: "~/Library/Logs/ss-local.log"]) } } @IBAction func feedback(_ sender: NSMenuItem) { - NSWorkspace.shared().open(URL(string: "https://github.com/shadowsocksr/ShadowsocksX-NG/issues")!) + NSWorkspace.shared.open(URL(string: "https://github.com/shadowsocksr/ShadowsocksX-NG/issues")!) } @IBAction func checkForUpdate(_ sender: NSMenuItem) { @@ -520,7 +520,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele @IBAction func checkUpdatesAtLaunch(_ sender: NSMenuItem) { let defaults = UserDefaults.standard defaults.set(!defaults.bool(forKey: "AutoCheckUpdate"), forKey: "AutoCheckUpdate") - checkUpdateAtLaunchMenuItem.state = defaults.bool(forKey: "AutoCheckUpdate") ? 1 : 0 + checkUpdateAtLaunchMenuItem.state = NSControl.StateValue(rawValue: defaults.bool(forKey: "AutoCheckUpdate") ? 1 : 0) } @IBAction func showAbout(_ sender: NSMenuItem) { @@ -529,7 +529,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele } func updateLaunchAtLoginMenu() { - lanchAtLoginMenuItem.state = launchAtLoginController.launchAtLogin ? 1 : 0 + lanchAtLoginMenuItem.state = NSControl.StateValue(rawValue: launchAtLoginController.launchAtLogin ? 1 : 0) } // MARK: this function is use to update menu bar @@ -559,34 +559,34 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele } serversMenuItem.title = serverMenuText - autoModeMenuItem.state = 0 - globalModeMenuItem.state = 0 - manualModeMenuItem.state = 0 - whiteListModeMenuItem.state = 0 - ACLBackChinaMenuItem.state = 0 - ACLAutoModeMenuItem.state = 0 - ACLModeMenuItem.state = 0 + autoModeMenuItem.state = NSControl.StateValue(rawValue: 0) + globalModeMenuItem.state = NSControl.StateValue(rawValue: 0) + manualModeMenuItem.state = NSControl.StateValue(rawValue: 0) + whiteListModeMenuItem.state = NSControl.StateValue(rawValue: 0) + ACLBackChinaMenuItem.state = NSControl.StateValue(rawValue: 0) + ACLAutoModeMenuItem.state = NSControl.StateValue(rawValue: 0) + ACLModeMenuItem.state = NSControl.StateValue(rawValue: 0) if mode == "auto" { - autoModeMenuItem.state = 1 + autoModeMenuItem.state = NSControl.StateValue(rawValue: 1) } else if mode == "global" { - globalModeMenuItem.state = 1 + globalModeMenuItem.state = NSControl.StateValue(rawValue: 1) } else if mode == "manual" { - manualModeMenuItem.state = 1 + manualModeMenuItem.state = NSControl.StateValue(rawValue: 1) } else if mode == "whiteList" { let aclMode = defaults.string(forKey: "ACLFileName")! switch aclMode { case "backchn.acl": - ACLModeMenuItem.state = 1 - ACLBackChinaMenuItem.state = 1 + ACLModeMenuItem.state = NSControl.StateValue(rawValue: 1) + ACLBackChinaMenuItem.state = NSControl.StateValue(rawValue: 1) ACLModeMenuItem.title = "Proxy Back China".localized break case "gfwlist.acl": - ACLModeMenuItem.state = 1 - ACLAutoModeMenuItem.state = 1 + ACLModeMenuItem.state = NSControl.StateValue(rawValue: 1) + ACLAutoModeMenuItem.state = NSControl.StateValue(rawValue: 1) ACLModeMenuItem.title = "ACL Auto".localized break default: - whiteListModeMenuItem.state = 1 + whiteListModeMenuItem.state = NSControl.StateValue(rawValue: 1) } } updateStatusItemUI() @@ -639,9 +639,9 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele statusItem!.image = image } - ShowNetworkSpeedItem.state = defaults.bool(forKey: "enable_showSpeed") ? 1 : 0 - connectAtLaunchMenuItem.state = defaults.bool(forKey: "ConnectAtLaunch") ? 1 : 0 - checkUpdateAtLaunchMenuItem.state = defaults.bool(forKey: "AutoCheckUpdate") ? 1 : 0 + ShowNetworkSpeedItem.state = NSControl.StateValue(rawValue: defaults.bool(forKey: "enable_showSpeed") ? 1 : 0) + connectAtLaunchMenuItem.state = NSControl.StateValue(rawValue: defaults.bool(forKey: "ConnectAtLaunch") ? 1 : 0) + checkUpdateAtLaunchMenuItem.state = NSControl.StateValue(rawValue: defaults.bool(forKey: "AutoCheckUpdate") ? 1 : 0) } func updateServersMenu() { @@ -671,7 +671,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele } } if mgr.getActiveProfileId() == p.uuid { - item.state = 1 + item.state = NSControl.StateValue(rawValue: 1) } if !p.isValid() { item.isEnabled = false @@ -687,8 +687,8 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele serversMenuItem.submenu?.addItem(groupSubmenuItem) serversMenuItem.submenu?.setSubmenu(groupSubmenu, for: groupSubmenuItem) if mgr.getActiveProfileId() == p.uuid { - item.state = 1 - groupSubmenuItem.state = 1 + item.state = NSControl.StateValue(rawValue: 1) + groupSubmenuItem.state = NSControl.StateValue(rawValue: 1) } groupSubmenuItem.submenu?.addItem(item) i += 1 @@ -696,8 +696,8 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele } else{ if mgr.getActiveProfileId() == p.uuid { - item.state = 1 - serversMenuItem.submenu?.item(withTitle: p.ssrGroup)?.state = 1 + item.state = NSControl.StateValue(rawValue: 1) + serversMenuItem.submenu?.item(withTitle: p.ssrGroup)?.state = NSControl.StateValue(rawValue: 1) } serversMenuItem.submenu?.item(withTitle: p.ssrGroup)?.submenu?.addItem(item) i += 1 @@ -713,7 +713,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele } serversMenuItem.submenu?.addItem(editSubscribeItem!) serversMenuItem.submenu?.addItem(autoUpdateSubscribeItem!) - autoUpdateSubscribeItem?.state = UserDefaults.standard.bool(forKey: "AutoUpdateSubscribe") ? 1 : 0 + autoUpdateSubscribeItem?.state = NSControl.StateValue(rawValue: UserDefaults.standard.bool(forKey: "AutoUpdateSubscribe") ? 1 : 0) serversMenuItem.submenu?.addItem(updateSubscribeItem!) serversMenuItem.submenu?.addItem(showQRItem!) serversMenuItem.submenu?.addItem(scanQRItem!) @@ -759,7 +759,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele let alertResult = versionChecker.showAlertView(Title: newVersion["Title"] as! String, SubTitle: newVersion["SubTitle"] as! String, ConfirmBtn: newVersion["ConfirmBtn"] as! String, CancelBtn: newVersion["CancelBtn"] as! String) print(alertResult) if (newVersion["newVersion"] as! Bool && alertResult == 1000){ - NSWorkspace.shared().open(URL(string: "https://github.com/qinyuhang/ShadowsocksX-NG-R/releases")!) + NSWorkspace.shared.open(URL(string: "https://github.com/qinyuhang/ShadowsocksX-NG-R/releases")!) } } } @@ -768,7 +768,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele // MARK: - func handleURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) { + @objc func handleURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) { if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue { if URL(string: urlString) != nil { NotificationCenter.default.post( diff --git a/ShadowsocksX-NG/NetWorkMonitor.swift b/ShadowsocksX-NG/NetWorkMonitor.swift index 490ff17..bcae372 100755 --- a/ShadowsocksX-NG/NetWorkMonitor.swift +++ b/ShadowsocksX-NG/NetWorkMonitor.swift @@ -24,7 +24,7 @@ open class NetWorkMonitor: NSObject { statusItemView.showSpeed = true } - func startUpdateTimer() { + @objc func startUpdateTimer() { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateNetWorkData), userInfo: nil, repeats: true) if #available(OSX 10.12, *){ @@ -32,7 +32,7 @@ open class NetWorkMonitor: NSObject { alertView.messageText = "网速显示不支持 macOS 10.12 Sierra!" alertView.informativeText = "因为 macOS 10.12 Sierra ABI 不稳定,因此暂时移除网速功能" alertView.addButton(withTitle: "取消网速显示") - _ = DispatchQueue.main.sync(execute: { Void in + _ = DispatchQueue.main.sync(execute: { alertView.runModal() }) stop() @@ -40,7 +40,7 @@ open class NetWorkMonitor: NSObject { // CFRunLoopRun() } else { - RunLoop.current.add(timer!, forMode: RunLoopMode.commonModes) + RunLoop.current.add(timer!, forMode: RunLoop.Mode.common) RunLoop.current.run() print(RunLoop.current.getCFRunLoop()) } @@ -53,7 +53,7 @@ open class NetWorkMonitor: NSObject { } - func updateNetWorkData() { + @objc func updateNetWorkData() { if Thread.current.isCancelled{ timer?.invalidate() @@ -121,8 +121,8 @@ open class NetWorkMonitor: NSObject { var upRate: Float = 0.00 var downRate: Float = 0.00 for result in results { - downRate += Float((string as NSString).substring(with: result.rangeAt(2)))! - upRate += Float((string as NSString).substring(with: result.rangeAt(4)))! + downRate += Float((string as NSString).substring(with: result.range(at: 2)))! + upRate += Float((string as NSString).substring(with: result.range(at: 4)))! } statusItemView.setRateData(up: upRate, down: downRate) } diff --git a/ShadowsocksX-NG/PingClient.swift b/ShadowsocksX-NG/PingClient.swift index d3b0ba5..7311848 100644 --- a/ShadowsocksX-NG/PingClient.swift +++ b/ShadowsocksX-NG/PingClient.swift @@ -160,8 +160,8 @@ class PingServers:NSObject{ } - (NSApplication.shared().delegate as! AppDelegate).updateServersMenu() - (NSApplication.shared().delegate as! AppDelegate).updateRunningModeMenu() + (NSApplication.shared.delegate as! AppDelegate).updateServersMenu() + (NSApplication.shared.delegate as! AppDelegate).updateRunningModeMenu() // do the UI update HERE if let min = result.min(by: {$0.1 < $1.1}){ diff --git a/ShadowsocksX-NG/PreferencesWindowController.swift b/ShadowsocksX-NG/PreferencesWindowController.swift index 61199d5..4451c71 100644 --- a/ShadowsocksX-NG/PreferencesWindowController.swift +++ b/ShadowsocksX-NG/PreferencesWindowController.swift @@ -95,7 +95,7 @@ class PreferencesWindowController: NSWindowController } override func awakeFromNib() { - profilesTableView.register(forDraggedTypes: [tableViewDragType]) + profilesTableView.registerForDraggedTypes([NSPasteboard.PasteboardType(rawValue: tableViewDragType)]) profilesTableView.allowsMultipleSelection = true } @@ -136,7 +136,7 @@ class PreferencesWindowController: NSWindowController updateProfileBoxVisible() if profileMgr.profiles.count == 0 { defaults.set(true, forKey: "ShadowsocksOn") - (NSApplication.shared().delegate as! AppDelegate).toggleRunning((NSApplication.shared().delegate as! AppDelegate).toggleRunningMenuItem) + (NSApplication.shared.delegate as! AppDelegate).toggleRunning((NSApplication.shared.delegate as! AppDelegate).toggleRunningMenuItem) } } @@ -192,9 +192,9 @@ class PreferencesWindowController: NSWindowController let ssURL = profile.URL() if let url = ssURL { - let pboard = NSPasteboard.general() + let pboard = NSPasteboard.general pboard.clearContents() - let rs = pboard.setString(String(describing: url), forType: NSStringPboardType)//writeObjects([url]) + let rs = pboard.setString(String(describing: url), forType: .string)//writeObjects([url]) if rs { NSLog("copy to pasteboard success") } else { @@ -223,42 +223,42 @@ class PreferencesWindowController: NSWindowController if index >= 0 && index < profileMgr.profiles.count { editingProfile = profileMgr.profiles[index] - hostTextField.bind("value", to: editingProfile, withKeyPath: "serverHost" - , options: [NSContinuouslyUpdatesValueBindingOption: true]) - portTextField.bind("value", to: editingProfile, withKeyPath: "serverPort" - , options: [NSContinuouslyUpdatesValueBindingOption: true]) + hostTextField.bind(NSBindingName(rawValue: "value"), to: editingProfile!, withKeyPath: "serverHost" + , options: [NSBindingOption.continuouslyUpdatesValue: true]) + portTextField.bind(NSBindingName(rawValue: "value"), to: editingProfile!, withKeyPath: "serverPort" + , options: [NSBindingOption.continuouslyUpdatesValue: true]) - methodTextField.bind("value", to: editingProfile, withKeyPath: "method" - , options: [NSContinuouslyUpdatesValueBindingOption: true]) - passwordTextField.bind("value", to: editingProfile, withKeyPath: "password" - , options: [NSContinuouslyUpdatesValueBindingOption: true]) + methodTextField.bind(NSBindingName(rawValue: "value"), to: editingProfile!, withKeyPath: "method" + , options: [NSBindingOption.continuouslyUpdatesValue: true]) + passwordTextField.bind(NSBindingName(rawValue: "value"), to: editingProfile!, withKeyPath: "password" + , options: [NSBindingOption.continuouslyUpdatesValue: true]) - remarkTextField.bind("value", to: editingProfile, withKeyPath: "remark" - , options: [NSContinuouslyUpdatesValueBindingOption: true]) + remarkTextField.bind(NSBindingName(rawValue: "value"), to: editingProfile!, withKeyPath: "remark" + , options: [NSBindingOption.continuouslyUpdatesValue: true]) - ProtocolTextField.bind("value", to: editingProfile, withKeyPath: "ssrProtocol", options: [NSContinuouslyUpdatesValueBindingOption: true]) + ProtocolTextField.bind(NSBindingName(rawValue: "value"), to: editingProfile!, withKeyPath: "ssrProtocol", options: [NSBindingOption.continuouslyUpdatesValue: true]) - ProtocolParamTextField.bind("value", to: editingProfile, withKeyPath: "ssrProtocolParam", options: [NSContinuouslyUpdatesValueBindingOption: true]) + ProtocolParamTextField.bind(NSBindingName(rawValue: "value"), to: editingProfile!, withKeyPath: "ssrProtocolParam", options: [NSBindingOption.continuouslyUpdatesValue: true]) - ObfsTextField.bind("value", to: editingProfile, withKeyPath: "ssrObfs", options: [NSContinuouslyUpdatesValueBindingOption: true]) + ObfsTextField.bind(NSBindingName(rawValue: "value"), to: editingProfile!, withKeyPath: "ssrObfs", options: [NSBindingOption.continuouslyUpdatesValue: true]) - ObfsParamTextField.bind("value", to: editingProfile, withKeyPath: "ssrObfsParam", options: [NSContinuouslyUpdatesValueBindingOption: true]) - groupTextField.bind("value", to: editingProfile, withKeyPath: "ssrGroup", options: [NSContinuouslyUpdatesValueBindingOption: true]) + ObfsParamTextField.bind(NSBindingName(rawValue: "value"), to: editingProfile!, withKeyPath: "ssrObfsParam", options: [NSBindingOption.continuouslyUpdatesValue: true]) + groupTextField.bind(NSBindingName(rawValue: "value"), to: editingProfile!, withKeyPath: "ssrGroup", options: [NSBindingOption.continuouslyUpdatesValue: true]) } else { editingProfile = nil - hostTextField.unbind("value") - portTextField.unbind("value") + hostTextField.unbind(NSBindingName(rawValue: "value")) + portTextField.unbind(NSBindingName(rawValue: "value")) - methodTextField.unbind("value") - passwordTextField.unbind("value") + methodTextField.unbind(NSBindingName(rawValue: "value")) + passwordTextField.unbind(NSBindingName(rawValue: "value")) - ProtocolTextField.unbind("value") - ProtocolParamTextField.unbind("value") - ObfsTextField.unbind("value") - ObfsParamTextField.unbind("value") + ProtocolTextField.unbind(NSBindingName(rawValue: "value")) + ProtocolParamTextField.unbind(NSBindingName(rawValue: "value")) + ObfsTextField.unbind(NSBindingName(rawValue: "value")) + ObfsParamTextField.unbind(NSBindingName(rawValue: "value")) - remarkTextField.unbind("value") + remarkTextField.unbind(NSBindingName(rawValue: "value")) } } @@ -289,9 +289,9 @@ class PreferencesWindowController: NSWindowController let (title, isActive) = getDataAtRow(row) - if tableColumn?.identifier == "main" { + if tableColumn!.identifier.rawValue == "main" { return title - } else if tableColumn?.identifier == "status" { + } else if tableColumn!.identifier.rawValue == "status" { if isActive { return NSImage(named: "NSMenuOnStateTemplate") } else { @@ -305,12 +305,12 @@ class PreferencesWindowController: NSWindowController func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? { let item = NSPasteboardItem() - item.setString(String(row), forType: tableViewDragType) + item.setString(String(row), forType: NSPasteboard.PasteboardType(rawValue: tableViewDragType)) return item } func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int - , proposedDropOperation dropOperation: NSTableViewDropOperation) -> NSDragOperation { + , proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation { if dropOperation == .above { return .move } @@ -318,14 +318,20 @@ class PreferencesWindowController: NSWindowController } func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo - , row: Int, dropOperation: NSTableViewDropOperation) -> Bool { + , row: Int, dropOperation: NSTableView.DropOperation) -> Bool { if let mgr = profileMgr { var oldIndexes = [Int]() - info.enumerateDraggingItems(options: [], for: tableView, classes: [NSPasteboardItem.self], searchOptions: [:]) { - if let str = ($0.0.item as! NSPasteboardItem).string(forType: self.tableViewDragType), let index = Int(str) { + info.enumerateDraggingItems( + options: [], + for: tableView, + classes: [NSPasteboardItem.self], + searchOptions: [:], + using: {(draggingItem, idx, stop) in + if let str = (draggingItem.item as! NSPasteboardItem).string(forType: NSPasteboard.PasteboardType(rawValue: self.tableViewDragType)), let index = Int(str) { oldIndexes.append(index) } - } + } + ) var oldIndexOffset = 0 var newIndexOffset = 0 diff --git a/ShadowsocksX-NG/ProxyPreferencesController.swift b/ShadowsocksX-NG/ProxyPreferencesController.swift index 168b061..3707e8f 100644 --- a/ShadowsocksX-NG/ProxyPreferencesController.swift +++ b/ShadowsocksX-NG/ProxyPreferencesController.swift @@ -70,9 +70,9 @@ class ProxyPreferencesController: NSWindowController, NSTableViewDataSource, NST let key = (networkServices[row] as AnyObject)["key"] as! String if selectedNetworkServices.contains(key) { - cell.state = 1 + cell.state = NSControl.StateValue(rawValue: 1) } else { - cell.state = 0 + cell.state = NSControl.StateValue(rawValue: 0) } let userDefinedName = (networkServices[row] as AnyObject)["userDefinedName"] as! String cell.title = userDefinedName diff --git a/ShadowsocksX-NG/ServerProfileManager.swift b/ShadowsocksX-NG/ServerProfileManager.swift index cbd13f8..454a723 100644 --- a/ShadowsocksX-NG/ServerProfileManager.swift +++ b/ShadowsocksX-NG/ServerProfileManager.swift @@ -129,7 +129,7 @@ class ServerProfileManager: NSObject { openPanel.becomeKey() openPanel.begin { (result) -> Void in // TODO not freeze the screen when running import process - if (result == NSFileHandlingPanelOKButton && (openPanel.url) != nil) { + if (result.rawValue == NSFileHandlingPanelOKButton && (openPanel.url) != nil) { let fileManager = FileManager.default let filePath:String = (openPanel.url?.path)! if (fileManager.fileExists(atPath: filePath) && filePath.hasSuffix("json")) { @@ -229,10 +229,10 @@ class ServerProfileManager: NSObject { savePanel.nameFieldStringValue = "export.json" savePanel.becomeKey() savePanel.begin { (result) -> Void in - if (result == NSFileHandlingPanelOKButton && (savePanel.url) != nil) { + if (result.rawValue == NSFileHandlingPanelOKButton && (savePanel.url) != nil) { //write jsonArr1 back to file try! jsonString.write(toFile: (savePanel.url?.path)!, atomically: true, encoding: String.Encoding.utf8) - NSWorkspace.shared().selectFile((savePanel.url?.path)!, inFileViewerRootedAtPath: (savePanel.directoryURL?.path)!) + NSWorkspace.shared.selectFile((savePanel.url?.path)!, inFileViewerRootedAtPath: (savePanel.directoryURL?.path)!) let notification = NSUserNotification() notification.title = "Export Server Profile succeed!".localized notification.informativeText = "Successful Export \(self.profiles.count) items".localized @@ -250,10 +250,10 @@ class ServerProfileManager: NSObject { let destPath = dataPath + "/example-gui-config.json" //检测文件是否已经存在,如果存在直接用sharedWorkspace显示 if fileMgr.fileExists(atPath: destPath) { - NSWorkspace.shared().selectFile(destPath, inFileViewerRootedAtPath: dataPath) + NSWorkspace.shared.selectFile(destPath, inFileViewerRootedAtPath: dataPath) }else{ try! fileMgr.copyItem(atPath: filePath, toPath: destPath) - NSWorkspace.shared().selectFile(destPath, inFileViewerRootedAtPath: dataPath) + NSWorkspace.shared.selectFile(destPath, inFileViewerRootedAtPath: dataPath) } } } diff --git a/ShadowsocksX-NG/StatusItemView.swift b/ShadowsocksX-NG/StatusItemView.swift index e1aa105..7d2573b 100755 --- a/ShadowsocksX-NG/StatusItemView.swift +++ b/ShadowsocksX-NG/StatusItemView.swift @@ -46,7 +46,7 @@ open class StatusItemView: NSControl { statusItem.drawStatusBarBackground(in: dirtyRect, withHighlight: mouseDown) fontColor = (darkMode||mouseDown) ? NSColor.white : NSColor.black - let fontAttributes = [NSFontAttributeName: NSFont.systemFont(ofSize: fontSize), NSForegroundColorAttributeName: fontColor] as [String : Any] + let fontAttributes = [NSAttributedString.Key.font.rawValue: NSFont.systemFont(ofSize: fontSize), NSAttributedString.Key.foregroundColor: fontColor] as! [NSAttributedString.Key : Any] if showSpeed{ let upRateString = NSAttributedString(string: upRate+" ↑", attributes: fontAttributes) let upRateRect = upRateString.boundingRect(with: NSSize(width: 100, height: 100), options: .usesLineFragmentOrigin) @@ -105,7 +105,7 @@ open class StatusItemView: NSControl { } } - func changeMode() { + @objc func changeMode() { darkMode = SystemThemeChangeHelper.isCurrentDark() setNeedsDisplay() } diff --git a/ShadowsocksX-NG/Subscribe.swift b/ShadowsocksX-NG/Subscribe.swift index 4df98ec..41a3d4d 100644 --- a/ShadowsocksX-NG/Subscribe.swift +++ b/ShadowsocksX-NG/Subscribe.swift @@ -152,7 +152,7 @@ class Subscribe: NSObject{ continue } if existResult { - self.profileMgr.profiles.replaceSubrange(Range(existIndex..= 0 && index < sbMgr.subscribes.count { editingSubscribe = sbMgr.subscribes[index] - FeedTextField.bind("value", to: editingSubscribe, withKeyPath: "subscribeFeed", options: [NSContinuouslyUpdatesValueBindingOption: true]) - TokenTextField.bind("value", to: editingSubscribe, withKeyPath: "token", options: [NSContinuouslyUpdatesValueBindingOption: true]) - GroupTextField.bind("value", to: editingSubscribe, withKeyPath: "groupName", options: [NSContinuouslyUpdatesValueBindingOption: true]) - MaxCountTextField.bind("value", to: editingSubscribe, withKeyPath: "maxCount", options: [NSContinuouslyUpdatesValueBindingOption: true]) + FeedTextField.bind(NSBindingName(rawValue: "value"), to: editingSubscribe!, withKeyPath: "subscribeFeed", options: [NSBindingOption.continuouslyUpdatesValue: true]) + TokenTextField.bind(NSBindingName(rawValue: "value"), to: editingSubscribe!, withKeyPath: "token", options: [NSBindingOption.continuouslyUpdatesValue: true]) + GroupTextField.bind(NSBindingName(rawValue: "value"), to: editingSubscribe!, withKeyPath: "groupName", options: [NSBindingOption.continuouslyUpdatesValue: true]) + MaxCountTextField.bind(NSBindingName(rawValue: "value"), to: editingSubscribe!, withKeyPath: "maxCount", options: [NSBindingOption.continuouslyUpdatesValue: true]) } else { editingSubscribe = nil - FeedTextField.unbind("value") - TokenTextField.unbind("value") - GroupTextField.unbind("value") - MaxCountTextField.unbind("value") + FeedTextField.unbind(NSBindingName(rawValue: "value")) + TokenTextField.unbind(NSBindingName(rawValue: "value")) + GroupTextField.unbind(NSBindingName(rawValue: "value")) + MaxCountTextField.unbind(NSBindingName(rawValue: "value")) } } @@ -148,10 +148,10 @@ class SubscribePreferenceWindowController: NSWindowController let title = getDataAtRow(row) - if tableColumn?.identifier == "main" { + if tableColumn!.identifier.rawValue == "main" { if title != "" {return title} else {return "S"} - } else if tableColumn?.identifier == "status" { + } else if tableColumn!.identifier.rawValue == "status" { return NSImage(named: "menu_icon") } return "" @@ -161,12 +161,12 @@ class SubscribePreferenceWindowController: NSWindowController func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? { let item = NSPasteboardItem() - item.setString(String(row), forType: tableViewDragType) + item.setString(String(row), forType: NSPasteboard.PasteboardType(rawValue: tableViewDragType)) return item } func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int - , proposedDropOperation dropOperation: NSTableViewDropOperation) -> NSDragOperation { + , proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation { if dropOperation == .above { return .move } @@ -174,14 +174,19 @@ class SubscribePreferenceWindowController: NSWindowController } func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo - , row: Int, dropOperation: NSTableViewDropOperation) -> Bool { + , row: Int, dropOperation: NSTableView.DropOperation) -> Bool { if let mgr = sbMgr { var oldIndexes = [Int]() - info.enumerateDraggingItems(options: [], for: tableView, classes: [NSPasteboardItem.self], searchOptions: [:]) { - if let str = ($0.0.item as! NSPasteboardItem).string(forType: self.tableViewDragType), let index = Int(str) { + info.enumerateDraggingItems( + options: [], + for: tableView, + classes: [NSPasteboardItem.self], + searchOptions: [:], + using: {(draggingItem, idx, stop) in + if let str = (draggingItem.item as! NSPasteboardItem).string(forType: NSPasteboard.PasteboardType(rawValue: self.tableViewDragType)), let index = Int(str) { oldIndexes.append(index) } - } + }) var oldIndexOffset = 0 var newIndexOffset = 0 diff --git a/ShadowsocksX-NG/UserRulesController.swift b/ShadowsocksX-NG/UserRulesController.swift index f378ca3..6b2dec5 100644 --- a/ShadowsocksX-NG/UserRulesController.swift +++ b/ShadowsocksX-NG/UserRulesController.swift @@ -22,7 +22,7 @@ class UserRulesController: NSWindowController { } let str = try? String(contentsOfFile: PACUserRuleFilePath, encoding: String.Encoding.utf8) - userRulesView.string = str + userRulesView.string = str ?? "" } @IBAction func didCancel(_ sender: AnyObject) { @@ -30,24 +30,23 @@ class UserRulesController: NSWindowController { } @IBAction func didOK(_ sender: AnyObject) { - if let str = userRulesView.string { - do { - try str.data(using: String.Encoding.utf8)?.write(to: URL(fileURLWithPath: PACUserRuleFilePath), options: .atomic) - - if GeneratePACFile() { - // Popup a user notification - let notification = NSUserNotification() - notification.title = "PAC has been updated by User Rules.".localized - NSUserNotificationCenter.default - .deliver(notification) - } else { - let notification = NSUserNotification() - notification.title = "It's failed to update PAC by User Rules.".localized - NSUserNotificationCenter.default - .deliver(notification) - } - } catch {} - } + let str = userRulesView.string + do { + try str.data(using: String.Encoding.utf8)?.write(to: URL(fileURLWithPath: PACUserRuleFilePath), options: .atomic) + + if GeneratePACFile() { + // Popup a user notification + let notification = NSUserNotification() + notification.title = "PAC has been updated by User Rules.".localized + NSUserNotificationCenter.default + .deliver(notification) + } else { + let notification = NSUserNotification() + notification.title = "It's failed to update PAC by User Rules.".localized + NSUserNotificationCenter.default + .deliver(notification) + } + } catch {} window?.performClose(self) } } diff --git a/ShadowsocksX-NG/VersionChecker.swift b/ShadowsocksX-NG/VersionChecker.swift index cecdfa6..904f68d 100644 --- a/ShadowsocksX-NG/VersionChecker.swift +++ b/ShadowsocksX-NG/VersionChecker.swift @@ -40,7 +40,7 @@ class VersionChecker: NSObject { alertView.addButton(withTitle: CancelBtn) } let action = alertView.runModal() - return action + return action.rawValue } func parserVersionString(strIn: String) -> Array{ var strTmp = strIn.substring(to: (strIn.range(of: "-")?.lowerBound)!)