From 34db2cb9ca0f431616128170dfbe9856a35b77f7 Mon Sep 17 00:00:00 2001 From: qinyuhang Date: Thu, 22 Sep 2016 20:17:12 +0800 Subject: [PATCH] convert project file from swift2.3 to swift3.0 --- ShadowsocksX-NG.xcodeproj/project.pbxproj | 25 +- .../AdvPreferencesWindowController.swift | 6 +- ShadowsocksX-NG/AppDelegate.swift | 228 +++++++++--------- ShadowsocksX-NG/LaunchAgentUtils.swift | 58 ++--- ShadowsocksX-NG/NetWorkMonitor.swift | 42 ++-- ShadowsocksX-NG/PACUtils.swift | 168 ++++++------- ShadowsocksX-NG/PingClient.swift | 49 ++-- ShadowsocksX-NG/PingTest.swift | 60 ++--- .../PreferencesWindowController.swift | 139 +++++------ .../ProxyPreferencesController.swift | 44 ++-- ShadowsocksX-NG/ServerProfile.swift | 88 +++---- ShadowsocksX-NG/ServerProfileManager.swift | 110 ++++----- ShadowsocksX-NG/StatusItemView.swift | 36 +-- ShadowsocksX-NG/SystemThemeChangeHelper.swift | 10 +- ShadowsocksX-NG/UserRulesController.swift | 24 +- ShadowsocksX-NG/Utils.swift | 12 +- .../ShadowsocksX_NGTests.swift | 2 +- 17 files changed, 560 insertions(+), 541 deletions(-) diff --git a/ShadowsocksX-NG.xcodeproj/project.pbxproj b/ShadowsocksX-NG.xcodeproj/project.pbxproj index 7f97608..e39d517 100644 --- a/ShadowsocksX-NG.xcodeproj/project.pbxproj +++ b/ShadowsocksX-NG.xcodeproj/project.pbxproj @@ -453,14 +453,17 @@ 9B0BFFE41D0460A70040E62B = { CreatedOnToolsVersion = 7.3.1; DevelopmentTeam = 2E8Q4BTFR2; + LastSwiftMigration = 0800; ProvisioningStyle = Automatic; }; 9B0BFFF31D0460A70040E62B = { CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 0800; TestTargetID = 9B0BFFE41D0460A70040E62B; }; 9B3FFF431D09CD3B0019A709 = { CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 0800; }; }; }; @@ -811,12 +814,12 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.11; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -851,10 +854,10 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.11; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; }; name = Release; }; @@ -879,12 +882,12 @@ "$(PROJECT_DIR)/ShadowsocksX-NG", "$(PROJECT_DIR)", ); - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.11; PRODUCT_BUNDLE_IDENTIFIER = "com.qiuyuzhou.ShadowsocksX-NG"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "ShadowsocksX-NG/ShadowsocksX-NG-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -909,11 +912,11 @@ "$(PROJECT_DIR)/ShadowsocksX-NG", "$(PROJECT_DIR)", ); - MACOSX_DEPLOYMENT_TARGET = 10.10; + MACOSX_DEPLOYMENT_TARGET = 10.11; PRODUCT_BUNDLE_IDENTIFIER = "com.qiuyuzhou.ShadowsocksX-NG"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "ShadowsocksX-NG/ShadowsocksX-NG-Bridging-Header.h"; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; }; name = Release; }; @@ -927,7 +930,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.qiuyuzhou.ShadowsocksX-NGTests"; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/ShadowsocksX-NG.app/Contents/MacOS/ShadowsocksX-NG"; }; name = Debug; @@ -942,7 +945,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.qiuyuzhou.ShadowsocksX-NGTests"; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/ShadowsocksX-NG.app/Contents/MacOS/ShadowsocksX-NG"; }; name = Release; @@ -953,6 +956,7 @@ buildSettings = { CODE_SIGN_IDENTITY = ""; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -962,6 +966,7 @@ buildSettings = { CODE_SIGN_IDENTITY = ""; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Release; }; diff --git a/ShadowsocksX-NG/AdvPreferencesWindowController.swift b/ShadowsocksX-NG/AdvPreferencesWindowController.swift index 806a4e4..e53a707 100644 --- a/ShadowsocksX-NG/AdvPreferencesWindowController.swift +++ b/ShadowsocksX-NG/AdvPreferencesWindowController.swift @@ -19,9 +19,9 @@ class AdvPreferencesWindowController: NSWindowController, NSWindowDelegate { //------------------------------------------------------------ // NSWindowDelegate - func windowWillClose(notification: NSNotification) { - NSNotificationCenter.defaultCenter() - .postNotificationName(NOTIFY_ADV_CONF_CHANGED, object: nil) + func windowWillClose(_ notification: Notification) { + NotificationCenter.default + .post(name: Notification.Name(rawValue: NOTIFY_ADV_CONF_CHANGED), object: nil) } } diff --git a/ShadowsocksX-NG/AppDelegate.swift b/ShadowsocksX-NG/AppDelegate.swift index 73f1da9..6f2a3d1 100644 --- a/ShadowsocksX-NG/AppDelegate.swift +++ b/ShadowsocksX-NG/AppDelegate.swift @@ -56,58 +56,58 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele // MARK: Application function - func applicationDidFinishLaunching(aNotification: NSNotification) { + func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application // PingServers.instance.ping() // let newInstance = PingTest.init(hostName: "www.baidu.com") // newInstance.start() let SerMgr = ServerProfileManager.instance - let pingServerQueue : dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0); + let pingServerQueue : DispatchQueue = DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.high); for profile in SerMgr.profiles { let host = profile.serverHost - dispatch_async(pingServerQueue, { + pingServerQueue.async(execute: { // print(profile.serverHost) let pingInstance = PingTest.init(hostName: host) pingInstance.start() })} - NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self + NSUserNotificationCenter.default.delegate = self // Prepare ss-local InstallSSLocal() // Prepare defaults - let defaults = NSUserDefaults.standardUserDefaults() - defaults.registerDefaults([ + let defaults = UserDefaults.standard + defaults.register(defaults: [ "ShadowsocksOn": true, "ShadowsocksRunningMode": "auto", - "LocalSocks5.ListenPort": NSNumber(unsignedShort: 1086), + "LocalSocks5.ListenPort": NSNumber(value: 1086 as UInt16), "LocalSocks5.ListenAddress": "127.0.0.1", "PacServer.ListenAddress": "127.0.0.1", - "PacServer.ListenPort":NSNumber(unsignedShort: 8090), - "LocalSocks5.Timeout": NSNumber(unsignedInteger: 60), - "LocalSocks5.EnableUDPRelay": NSNumber(bool: false), - "LocalSocks5.EnableVerboseMode": NSNumber(bool: false), + "PacServer.ListenPort":NSNumber(value: 8090 as UInt16), + "LocalSocks5.Timeout": NSNumber(value: 60 as UInt), + "LocalSocks5.EnableUDPRelay": NSNumber(value: false as Bool), + "LocalSocks5.EnableVerboseMode": NSNumber(value: false as Bool), "GFWListURL": "https://raw.githubusercontent.com/gfwlist/gfwlist/master/gfwlist.txt", "WhiteListURL": "https://raw.githubusercontent.com/breakwa11/gfw_whitelist/master/whitelist.pac", "WhiteListIPURL": "https://raw.githubusercontent.com/breakwa11/gfw_whitelist/master/whiteiplist.pac", - "AutoConfigureNetworkServices": NSNumber(bool: true) + "AutoConfigureNetworkServices": NSNumber(value: true as Bool) ]) - setUpMenu(defaults.boolForKey("enable_showSpeed")) + setUpMenu(defaults.bool(forKey: "enable_showSpeed")) - let notifyCenter = NSNotificationCenter.defaultCenter() - notifyCenter.addObserverForName(NOTIFY_ADV_PROXY_CONF_CHANGED, object: nil, queue: nil - , usingBlock: { + let notifyCenter = NotificationCenter.default + notifyCenter.addObserver(forName: NSNotification.Name(rawValue: NOTIFY_ADV_PROXY_CONF_CHANGED), object: nil, queue: nil + , using: { (note) in self.applyConfig() } ) - notifyCenter.addObserverForName(NOTIFY_SERVER_PROFILES_CHANGED, object: nil, queue: nil - , usingBlock: { + notifyCenter.addObserver(forName: NSNotification.Name(rawValue: NOTIFY_SERVER_PROFILES_CHANGED), object: nil, queue: nil + , using: { (note) in let profileMgr = ServerProfileManager.instance if profileMgr.activeProfileId == nil && @@ -120,17 +120,17 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele SyncSSLocal() } ) - notifyCenter.addObserverForName(NOTIFY_ADV_CONF_CHANGED, object: nil, queue: nil - , usingBlock: { + notifyCenter.addObserver(forName: NSNotification.Name(rawValue: NOTIFY_ADV_CONF_CHANGED), object: nil, queue: nil + , using: { (note) in SyncSSLocal() self.applyConfig() } ) - notifyCenter.addObserverForName("NOTIFY_FOUND_SS_URL", object: nil, queue: nil) { - (note: NSNotification) in - if let userInfo = note.userInfo { - let urls: [NSURL] = userInfo["urls"] as! [NSURL] + notifyCenter.addObserver(forName: NSNotification.Name(rawValue: "NOTIFY_FOUND_SS_URL"), object: nil, queue: nil) { + (note: Notification) in + if let userInfo = (note as NSNotification).userInfo { + let urls: [URL] = userInfo["urls"] as! [URL] let mgr = ServerProfileManager.instance var isChanged = false @@ -138,7 +138,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele for url in urls { let profielDict = ParseSSURL(url) if let profielDict = profielDict { - let profile = ServerProfile.fromDictionary(profielDict) + let profile = ServerProfile.fromDictionary(profielDict as [String : AnyObject]) mgr.profiles.append(profile) isChanged = true @@ -154,14 +154,14 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele " Encription Method: \(profile.method)".localized userNote.soundName = NSUserNotificationDefaultSoundName - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(userNote); + NSUserNotificationCenter.default + .deliver(userNote); }else{ let userNote = NSUserNotification() userNote.title = "Failed to Add Server Profile".localized userNote.subtitle = "Address can't not be recognized".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(userNote); + NSUserNotificationCenter.default + .deliver(userNote); } } @@ -173,7 +173,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele } // Handle ss url scheme - NSAppleEventManager.sharedAppleEventManager().setEventHandler(self + NSAppleEventManager.shared().setEventHandler(self , andSelector: #selector(self.handleURLEvent) , forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL)) @@ -186,19 +186,19 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele applyConfig() SyncSSLocal() - if defaults.boolForKey("ConnectAtLaunch") { + if defaults.bool(forKey: "ConnectAtLaunch") { toggleRunning(toggleRunningMenuItem) } } - func applicationWillTerminate(aNotification: NSNotification) { + func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application StopSSLocal() ProxyConfHelper.disableProxy("hi") - let defaults = NSUserDefaults.standardUserDefaults() - defaults.setBool(false, forKey: "ShadowsocksOn") + let defaults = UserDefaults.standard + defaults.set(false, forKey: "ShadowsocksOn") ProxyConfHelper.stopPACServer() } @@ -208,11 +208,11 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele let notice = NSUserNotification() notice.title = "还没有服务器设定!" notice.subtitle = "去设置里面填一下吧,填完记得选择呦~" - NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notice) + NSUserNotificationCenter.default.deliver(notice) } - let defaults = NSUserDefaults.standardUserDefaults() - let isOn = defaults.boolForKey("ShadowsocksOn") - let mode = defaults.stringForKey("ShadowsocksRunningMode") + let defaults = UserDefaults.standard + let isOn = defaults.bool(forKey: "ShadowsocksOn") + let mode = defaults.string(forKey: "ShadowsocksRunningMode") if isOn { StartSSLocal() @@ -241,26 +241,26 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele // MARK: Mainmenu functions - @IBAction func toggleRunning(sender: NSMenuItem) { - let defaults = NSUserDefaults.standardUserDefaults() - var isOn = defaults.boolForKey("ShadowsocksOn") + @IBAction func toggleRunning(_ sender: NSMenuItem) { + let defaults = UserDefaults.standard + var isOn = defaults.bool(forKey: "ShadowsocksOn") isOn = !isOn - defaults.setBool(isOn, forKey: "ShadowsocksOn") + defaults.set(isOn, forKey: "ShadowsocksOn") updateMainMenu() applyConfig() } - @IBAction func updateGFWList(sender: NSMenuItem) { + @IBAction func updateGFWList(_ sender: NSMenuItem) { UpdatePACFromGFWList() } - @IBAction func updateWhiteList(sender: NSMenuItem) { + @IBAction func updateWhiteList(_ sender: NSMenuItem) { UpdatePACFromWhiteList() } - @IBAction func editUserRulesForPAC(sender: NSMenuItem) { + @IBAction func editUserRulesForPAC(_ sender: NSMenuItem) { if editUserRulesWinCtrl != nil { editUserRulesWinCtrl.close() } @@ -268,23 +268,23 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele editUserRulesWinCtrl = ctrl ctrl.showWindow(self) - NSApp.activateIgnoringOtherApps(true) + NSApp.activate(ignoringOtherApps: true) ctrl.window?.makeKeyAndOrderFront(self) } - @IBAction func toggleLaunghAtLogin(sender: NSMenuItem) { + @IBAction func toggleLaunghAtLogin(_ sender: NSMenuItem) { launchAtLoginController.launchAtLogin = !launchAtLoginController.launchAtLogin; updateLaunchAtLoginMenu() } - @IBAction func toggleConnectAtLaunch(sender: NSMenuItem) { - let defaults = NSUserDefaults.standardUserDefaults() - defaults.setBool(!defaults.boolForKey("ConnectAtLaunch"), forKey: "ConnectAtLaunch") + @IBAction func toggleConnectAtLaunch(_ sender: NSMenuItem) { + let defaults = UserDefaults.standard + defaults.set(!defaults.bool(forKey: "ConnectAtLaunch"), forKey: "ConnectAtLaunch") updateMainMenu() } // MARK: Server submenu function - @IBAction func showQRCodeForCurrentServer(sender: NSMenuItem) { + @IBAction func showQRCodeForCurrentServer(_ sender: NSMenuItem) { var errMsg: String? if let profile = ServerProfileManager.instance.getActiveProfile() { if profile.isValid() { @@ -295,7 +295,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele qrcodeWinCtrl = SWBQRCodeWindowController(windowNibName: "SWBQRCodeWindowController") qrcodeWinCtrl.qrCode = profile.URL()!.absoluteString qrcodeWinCtrl.showWindow(self) - NSApp.activateIgnoringOtherApps(true) + NSApp.activate(ignoringOtherApps: true) qrcodeWinCtrl.window?.makeKeyAndOrderFront(nil) return @@ -309,63 +309,63 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele userNote.title = errMsg userNote.soundName = NSUserNotificationDefaultSoundName - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(userNote); + NSUserNotificationCenter.default + .deliver(userNote); } - @IBAction func scanQRCodeFromScreen(sender: NSMenuItem) { + @IBAction func scanQRCodeFromScreen(_ sender: NSMenuItem) { ScanQRCodeOnScreen() } - @IBAction func showBunchJsonExampleFile(sender: NSMenuItem) { + @IBAction func showBunchJsonExampleFile(_ sender: NSMenuItem) { ServerProfileManager.showExampleConfigFile() } - @IBAction func importBunchJsonFile(sender: NSMenuItem) { + @IBAction func importBunchJsonFile(_ sender: NSMenuItem) { ServerProfileManager.instance.importConfigFile() //updateServersMenu()//not working } - @IBAction func exportAllServerProfile(sender: NSMenuItem) { + @IBAction func exportAllServerProfile(_ sender: NSMenuItem) { ServerProfileManager.instance.exportConfigFile() } - @IBAction func selectPACMode(sender: NSMenuItem) { - let defaults = NSUserDefaults.standardUserDefaults() + @IBAction func selectPACMode(_ sender: NSMenuItem) { + let defaults = UserDefaults.standard defaults.setValue("auto", forKey: "ShadowsocksRunningMode") updateRunningModeMenu() applyConfig() } - @IBAction func selectGlobalMode(sender: NSMenuItem) { - let defaults = NSUserDefaults.standardUserDefaults() + @IBAction func selectGlobalMode(_ sender: NSMenuItem) { + let defaults = UserDefaults.standard defaults.setValue("global", forKey: "ShadowsocksRunningMode") updateRunningModeMenu() applyConfig() } - @IBAction func selectManualMode(sender: NSMenuItem) { - let defaults = NSUserDefaults.standardUserDefaults() + @IBAction func selectManualMode(_ sender: NSMenuItem) { + let defaults = UserDefaults.standard defaults.setValue("manual", forKey: "ShadowsocksRunningMode") updateRunningModeMenu() applyConfig() } - @IBAction func selectWhiteDomainListMode(sender: NSMenuItem) { - let defaults = NSUserDefaults.standardUserDefaults() + @IBAction func selectWhiteDomainListMode(_ sender: NSMenuItem) { + let defaults = UserDefaults.standard defaults.setValue("whiteListDomain", forKey: "ShadowsocksRunningMode") updateRunningModeMenu() applyConfig() } - @IBAction func selectWhiteIPListMode(sender: NSMenuItem) { - let defaults = NSUserDefaults.standardUserDefaults() + @IBAction func selectWhiteIPListMode(_ sender: NSMenuItem) { + let defaults = UserDefaults.standard defaults.setValue("whiteListIP", forKey: "ShadowsocksRunningMode") updateRunningModeMenu() applyConfig() } - @IBAction func editServerPreferences(sender: NSMenuItem) { + @IBAction func editServerPreferences(_ sender: NSMenuItem) { if preferencesWinCtrl != nil { preferencesWinCtrl.close() } @@ -373,11 +373,11 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele preferencesWinCtrl = ctrl ctrl.showWindow(self) - NSApp.activateIgnoringOtherApps(true) + NSApp.activate(ignoringOtherApps: true) ctrl.window?.makeKeyAndOrderFront(self) } - @IBAction func editAdvPreferences(sender: NSMenuItem) { + @IBAction func editAdvPreferences(_ sender: NSMenuItem) { if advPreferencesWinCtrl != nil { advPreferencesWinCtrl.close() } @@ -385,21 +385,21 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele advPreferencesWinCtrl = ctrl ctrl.showWindow(self) - NSApp.activateIgnoringOtherApps(true) + NSApp.activate(ignoringOtherApps: true) ctrl.window?.makeKeyAndOrderFront(self) } - @IBAction func editProxyPreferences(sender: NSObject) { + @IBAction func editProxyPreferences(_ sender: NSObject) { if proxyPreferencesWinCtrl != nil { proxyPreferencesWinCtrl.close() } proxyPreferencesWinCtrl = ProxyPreferencesController(windowNibName: "ProxyPreferencesController") proxyPreferencesWinCtrl.showWindow(self) - NSApp.activateIgnoringOtherApps(true) + NSApp.activate(ignoringOtherApps: true) proxyPreferencesWinCtrl.window?.makeKeyAndOrderFront(self) } - @IBAction func selectServer(sender: NSMenuItem) { + @IBAction func selectServer(_ sender: NSMenuItem) { let index = sender.tag let spMgr = ServerProfileManager.instance let newProfile = spMgr.profiles[index] @@ -411,35 +411,35 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele updateRunningModeMenu() } - @IBAction func doPingTest(sender: AnyObject) { + @IBAction func doPingTest(_ sender: AnyObject) { PingServers.instance.ping() } - @IBAction func showSpeedTap(sender: NSMenuItem) { - let defaults = NSUserDefaults.standardUserDefaults() - var enable = defaults.boolForKey("enable_showSpeed") + @IBAction func showSpeedTap(_ sender: NSMenuItem) { + let defaults = UserDefaults.standard + var enable = defaults.bool(forKey: "enable_showSpeed") enable = !enable setUpMenu(enable) - defaults.setBool(enable, forKey: "enable_showSpeed") + defaults.set(enable, forKey: "enable_showSpeed") updateMainMenu() } - @IBAction func showLogs(sender: NSMenuItem) { - let ws = NSWorkspace.sharedWorkspace() - if let appUrl = ws.URLForApplicationWithBundleIdentifier("com.apple.Console") { - try! ws.launchApplicationAtURL(appUrl - ,options: .Default + @IBAction func showLogs(_ sender: NSMenuItem) { + 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"]) } } - @IBAction func feedback(sender: NSMenuItem) { - NSWorkspace.sharedWorkspace().openURL(NSURL(string: "https://github.com/qinyuhang/ShadowsocksX-NG/issues")!) + @IBAction func feedback(_ sender: NSMenuItem) { + NSWorkspace.shared().open(URL(string: "https://github.com/qinyuhang/ShadowsocksX-NG/issues")!) } - @IBAction func showAbout(sender: NSMenuItem) { + @IBAction func showAbout(_ sender: NSMenuItem) { NSApp.orderFrontStandardAboutPanel(sender); - NSApp.activateIgnoringOtherApps(true) + NSApp.activate(ignoringOtherApps: true) } func updateLaunchAtLoginMenu() { @@ -453,8 +453,8 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele // MARK: this function is use to update menu bar func updateRunningModeMenu() { - let defaults = NSUserDefaults.standardUserDefaults() - let mode = defaults.stringForKey("ShadowsocksRunningMode") + let defaults = UserDefaults.standard + let mode = defaults.string(forKey: "ShadowsocksRunningMode") var serverMenuText = "Servers".localized let mgr = ServerProfileManager.instance @@ -516,8 +516,8 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele } func updateMainMenu() { - let defaults = NSUserDefaults.standardUserDefaults() - let isOn = defaults.boolForKey("ShadowsocksOn") + let defaults = UserDefaults.standard + let isOn = defaults.bool(forKey: "ShadowsocksOn") if isOn { runningStatusMenuItem.title = "Shadowsocks: On".localized toggleRunningMenuItem.title = "Turn Shadowsocks Off".localized @@ -539,13 +539,13 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele statusItemView.setIcon(image!) } - if defaults.boolForKey("enable_showSpeed") { + if defaults.bool(forKey: "enable_showSpeed") { ShowNetworkSpeedItem.state = 1 }else{ ShowNetworkSpeedItem.state = 0 } - if defaults.boolForKey("ConnectAtLaunch") { + if defaults.bool(forKey: "ConnectAtLaunch") { connectAtLaunchMenuItem.state = 1 } else { connectAtLaunchMenuItem.state = 0 @@ -581,7 +581,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele item.state = 1 } if !p.isValid() { - item.enabled = false + item.isEnabled = false } item.action = #selector(AppDelegate.selectServer) @@ -589,24 +589,24 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele i += 1 } if !mgr.profiles.isEmpty { - serversMenuItem.submenu?.addItem(NSMenuItem.separatorItem()) + serversMenuItem.submenu?.addItem(NSMenuItem.separator()) } - serversMenuItem.submenu?.addItem(showQRItem) - serversMenuItem.submenu?.addItem(scanQRItem) - serversMenuItem.submenu?.addItem(showBunch) - serversMenuItem.submenu?.addItem(importBuntch) - serversMenuItem.submenu?.addItem(exportAllServer) - serversMenuItem.submenu?.addItem(NSMenuItem.separatorItem()) - serversMenuItem.submenu?.addItem(preferencesItem) + serversMenuItem.submenu?.addItem(showQRItem!) + serversMenuItem.submenu?.addItem(scanQRItem!) + serversMenuItem.submenu?.addItem(showBunch!) + serversMenuItem.submenu?.addItem(importBuntch!) + serversMenuItem.submenu?.addItem(exportAllServer!) + serversMenuItem.submenu?.addItem(NSMenuItem.separator()) + serversMenuItem.submenu?.addItem(preferencesItem!) // serversMenuItem.submenu?.addItem(pingItem) } - func setUpMenu(showSpeed:Bool){ + func setUpMenu(_ showSpeed:Bool){ if statusItem == nil{ - statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(85) + statusItem = NSStatusBar.system().statusItem(withLength: 85) let image = NSImage(named: "menu_icon") - image?.template = true + image?.isTemplate = true statusItem!.image = image statusItemView = StatusItemView(statusItem: statusItem!, menu: statusMenu) statusItem!.view = statusItemView @@ -626,11 +626,11 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele // MARK: - func handleURLEvent(event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) { - if let urlString = event.paramDescriptorForKeyword(AEKeyword(keyDirectObject))?.stringValue { - if let url = NSURL(string: urlString) { - NSNotificationCenter.defaultCenter().postNotificationName( - "NOTIFY_FOUND_SS_URL", object: nil + func handleURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) { + if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue { + if let url = URL(string: urlString) { + NotificationCenter.default.post( + name: Notification.Name(rawValue: "NOTIFY_FOUND_SS_URL"), object: nil , userInfo: [ "ruls": [url], "source": "url", @@ -642,8 +642,8 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele //------------------------------------------------------------ // MARK: NSUserNotificationCenterDelegate - func userNotificationCenter(center: NSUserNotificationCenter - , shouldPresentNotification notification: NSUserNotification) -> Bool { + func userNotificationCenter(_ center: NSUserNotificationCenter + , shouldPresent notification: NSUserNotification) -> Bool { return true } } diff --git a/ShadowsocksX-NG/LaunchAgentUtils.swift b/ShadowsocksX-NG/LaunchAgentUtils.swift index 9f7a7b3..34b3cad 100644 --- a/ShadowsocksX-NG/LaunchAgentUtils.swift +++ b/ShadowsocksX-NG/LaunchAgentUtils.swift @@ -14,8 +14,8 @@ let LAUNCH_AGENT_DIR = "/Library/LaunchAgents/" let LAUNCH_AGENT_CONF_NAME = "com.qiuyuzhou.shadowsocksX-NG.local.plist" -func getFileSHA1Sum(filepath: String) -> String { - if let data = NSData(contentsOfFile: filepath) { +func getFileSHA1Sum(_ filepath: String) -> String { + if let data = try? Data(contentsOf: URL(fileURLWithPath: filepath)) { return data.sha1() } return "" @@ -30,16 +30,16 @@ func generateSSLocalLauchAgentPlist() -> Bool { let plistFilepath = launchAgentDirPath + LAUNCH_AGENT_CONF_NAME // Ensure launch agent directory is existed. - let fileMgr = NSFileManager.defaultManager() - if !fileMgr.fileExistsAtPath(launchAgentDirPath) { - try! fileMgr.createDirectoryAtPath(launchAgentDirPath, withIntermediateDirectories: true, attributes: nil) + let fileMgr = FileManager.default + if !fileMgr.fileExists(atPath: launchAgentDirPath) { + try! fileMgr.createDirectory(atPath: launchAgentDirPath, withIntermediateDirectories: true, attributes: nil) } let oldSha1Sum = getFileSHA1Sum(plistFilepath) - let defaults = NSUserDefaults.standardUserDefaults() - let enableUdpRelay = defaults.boolForKey("LocalSocks5.EnableUDPRelay") - let enableVerboseMode = defaults.boolForKey("LocalSocks5.EnableVerboseMode") + let defaults = UserDefaults.standard + let enableUdpRelay = defaults.bool(forKey: "LocalSocks5.EnableUDPRelay") + let enableVerboseMode = defaults.bool(forKey: "LocalSocks5.EnableVerboseMode") var arguments = [sslocalPath, "-c", "ss-local-config.json"] if enableUdpRelay { @@ -59,7 +59,7 @@ func generateSSLocalLauchAgentPlist() -> Bool { "ProgramArguments": arguments, "EnvironmentVariables": ["DYLD_LIBRARY_PATH": NSHomeDirectory() + APP_SUPPORT_DIR] ] - dict.writeToFile(plistFilepath, atomically: true) + dict.write(toFile: plistFilepath, atomically: true) let Sha1Sum = getFileSHA1Sum(plistFilepath) if oldSha1Sum != Sha1Sum { return true @@ -69,9 +69,9 @@ func generateSSLocalLauchAgentPlist() -> Bool { } func ReloadConfSSLocal() { - let bundle = NSBundle.mainBundle() - let installerPath = bundle.pathForResource("reload_conf_ss_local.sh", ofType: nil) - let task = NSTask.launchedTaskWithLaunchPath(installerPath!, arguments: [""]) + let bundle = Bundle.main + let installerPath = bundle.path(forResource: "reload_conf_ss_local.sh", ofType: nil) + let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Start ss-local succeeded.") @@ -81,9 +81,9 @@ func ReloadConfSSLocal() { } func StartSSLocal() { - let bundle = NSBundle.mainBundle() - let installerPath = bundle.pathForResource("start_ss_local.sh", ofType: nil) - let task = NSTask.launchedTaskWithLaunchPath(installerPath!, arguments: [""]) + let bundle = Bundle.main + let installerPath = bundle.path(forResource: "start_ss_local.sh", ofType: nil) + let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Start ss-local succeeded.") @@ -93,9 +93,9 @@ func StartSSLocal() { } func StopSSLocal() { - let bundle = NSBundle.mainBundle() - let installerPath = bundle.pathForResource("stop_ss_local.sh", ofType: nil) - let task = NSTask.launchedTaskWithLaunchPath(installerPath!, arguments: [""]) + let bundle = Bundle.main + let installerPath = bundle.path(forResource: "stop_ss_local.sh", ofType: nil) + let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Stop ss-local succeeded.") @@ -105,14 +105,14 @@ func StopSSLocal() { } func InstallSSLocal() { - let fileMgr = NSFileManager.defaultManager() + let fileMgr = FileManager.default let homeDir = NSHomeDirectory() let appSupportDir = homeDir+APP_SUPPORT_DIR - if !fileMgr.fileExistsAtPath(appSupportDir + "ss-local-\(SS_LOCAL_VERSION)/ss-local") - || !fileMgr.fileExistsAtPath(appSupportDir + "libcrypto.1.0.0.dylib") { - let bundle = NSBundle.mainBundle() - let installerPath = bundle.pathForResource("install_ss_local.sh", ofType: nil) - let task = NSTask.launchedTaskWithLaunchPath(installerPath!, arguments: [""]) + if !fileMgr.fileExists(atPath: appSupportDir + "ss-local-\(SS_LOCAL_VERSION)/ss-local") + || !fileMgr.fileExists(atPath: appSupportDir + "libcrypto.1.0.0.dylib") { + let bundle = Bundle.main + let installerPath = bundle.path(forResource: "install_ss_local.sh", ofType: nil) + let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Install ss-local succeeded.") @@ -122,13 +122,13 @@ func InstallSSLocal() { } } -func writeSSLocalConfFile(conf:[String:AnyObject]) -> Bool { +func writeSSLocalConfFile(_ conf:[String:AnyObject]) -> Bool { do { let filepath = NSHomeDirectory() + APP_SUPPORT_DIR + "ss-local-config.json" - let data: NSData = try NSJSONSerialization.dataWithJSONObject(conf, options: .PrettyPrinted) + let data: Data = try JSONSerialization.data(withJSONObject: conf, options: .prettyPrinted) let oldSum = getFileSHA1Sum(filepath) - try data.writeToFile(filepath, options: .DataWritingAtomic) + try data.write(to: URL(fileURLWithPath: filepath), options: .atomic) let newSum = getFileSHA1Sum(filepath) if oldSum == newSum { @@ -145,7 +145,7 @@ func writeSSLocalConfFile(conf:[String:AnyObject]) -> Bool { func removeSSLocalConfFile() { do { let filepath = NSHomeDirectory() + APP_SUPPORT_DIR + "ss-local-config.json" - try NSFileManager.defaultManager().removeItemAtPath(filepath) + try FileManager.default.removeItem(atPath: filepath) } catch { } @@ -158,7 +158,7 @@ func SyncSSLocal() { if mgr.activeProfileId != nil { changed = changed || writeSSLocalConfFile((mgr.getActiveProfile()?.toJsonConfig())!) - let on = NSUserDefaults.standardUserDefaults().boolForKey("ShadowsocksOn") + let on = UserDefaults.standard.bool(forKey: "ShadowsocksOn") if on { StartSSLocal() ReloadConfSSLocal() diff --git a/ShadowsocksX-NG/NetWorkMonitor.swift b/ShadowsocksX-NG/NetWorkMonitor.swift index f8888fe..e2c113d 100755 --- a/ShadowsocksX-NG/NetWorkMonitor.swift +++ b/ShadowsocksX-NG/NetWorkMonitor.swift @@ -8,31 +8,31 @@ import Foundation -public class NetWorkMonitor: NSObject { +open class NetWorkMonitor: NSObject { let statusItemView: StatusItemView - var thread:NSThread? - var timer:NSTimer? + var thread:Thread? + var timer:Timer? init(statusItemView view: StatusItemView) { statusItemView = view } func start() { - thread = NSThread(target: self, selector: #selector(startUpdateTimer), object: nil) + thread = Thread(target: self, selector: #selector(startUpdateTimer), object: nil) thread?.start() statusItemView.showSpeed = true } func startUpdateTimer() { - timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(updateNetWorkData), userInfo: nil, repeats: true) + timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateNetWorkData), userInfo: nil, repeats: true) if #available(OSX 10.12, *){ let alertView = NSAlert() alertView.messageText = "网速显示不支持 macOS 10.12 Sierra!" alertView.informativeText = "因为 macOS 10.12 Sierra ABI 不稳定,因此暂时移除网速功能" - alertView.addButtonWithTitle("取消网速显示") - dispatch_sync(dispatch_get_main_queue(), { Void in + alertView.addButton(withTitle: "取消网速显示") + DispatchQueue.main.sync(execute: { Void in alertView.runModal() }) stop() @@ -40,9 +40,9 @@ public class NetWorkMonitor: NSObject { // CFRunLoopRun() } else { - NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes) - NSRunLoop.currentRunLoop().run() - print(NSRunLoop.currentRunLoop().getCFRunLoop()) + RunLoop.current.add(timer!, forMode: RunLoopMode.commonModes) + RunLoop.current.run() + print(RunLoop.current.getCFRunLoop()) } } @@ -55,19 +55,19 @@ public class NetWorkMonitor: NSObject { func updateNetWorkData() { - if NSThread.currentThread().cancelled{ + if Thread.current.isCancelled{ timer?.invalidate() timer = nil thread = nil - NSThread.exit() + Thread.exit() } - let task = NSTask() + let task = Process() task.launchPath = "/usr/bin/sar" task.arguments = ["-n", "DEV", "1"] - let pipe = NSPipe() + let pipe = Pipe() task.standardOutput = pipe task.launch() @@ -79,8 +79,8 @@ public class NetWorkMonitor: NSObject { let fileHandle = pipe.fileHandleForReading let data = fileHandle.readDataToEndOfFile() - var string = String(data: data, encoding: NSUTF8StringEncoding) - string = string?.substringFromIndex((string?.rangeOfString("Aver")?.startIndex)!) + var string = String(data: data, encoding: String.Encoding.utf8) + string = string?.substring(from: (string?.range(of: "Aver")?.lowerBound)!) handleNetWorkData(string!) } else { print("Task failed.") @@ -112,17 +112,17 @@ public class NetWorkMonitor: NSObject { Average: bridge0 0 0 0 0 Average: en4 0 0 0 0 */ - func handleNetWorkData(string: String) { + func handleNetWorkData(_ string: String) { // print(string) let pattern = "en\\w+\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)" do { - let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive) - let results = regex.matchesInString(string, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, string.characters.count)) + let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive) + let results = regex.matches(in: string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, string.characters.count)) var upRate: Float = 0.00 var downRate: Float = 0.00 for result in results { - downRate += Float((string as NSString).substringWithRange(result.rangeAtIndex(2)))! - upRate += Float((string as NSString).substringWithRange(result.rangeAtIndex(4)))! + downRate += Float((string as NSString).substring(with: result.rangeAt(2)))! + upRate += Float((string as NSString).substring(with: result.rangeAt(4)))! } statusItemView.setRateData(up: upRate, down: downRate) } diff --git a/ShadowsocksX-NG/PACUtils.swift b/ShadowsocksX-NG/PACUtils.swift index 4a96028..ee3d3b9 100644 --- a/ShadowsocksX-NG/PACUtils.swift +++ b/ShadowsocksX-NG/PACUtils.swift @@ -23,75 +23,75 @@ let WhiteListIPPACFilePath = PACRulesDirPath + "whiteiplist.pac" func SyncPac() { var needGenerate = false - let nowSocks5Port = NSUserDefaults.standardUserDefaults().integerForKey("LocalSocks5.ListenPort") - let oldSocks5Port = NSUserDefaults.standardUserDefaults().integerForKey("LocalSocks5.ListenPort.Old") + let nowSocks5Port = UserDefaults.standard.integer(forKey: "LocalSocks5.ListenPort") + let oldSocks5Port = UserDefaults.standard.integer(forKey: "LocalSocks5.ListenPort.Old") if nowSocks5Port != oldSocks5Port { needGenerate = true - NSUserDefaults.standardUserDefaults().setInteger(nowSocks5Port, forKey: "LocalSocks5.ListenPort.Old") + UserDefaults.standard.set(nowSocks5Port, forKey: "LocalSocks5.ListenPort.Old") } - let fileMgr = NSFileManager.defaultManager() - if !fileMgr.fileExistsAtPath(PACRulesDirPath) { + let fileMgr = FileManager.default + if !fileMgr.fileExists(atPath: PACRulesDirPath) { needGenerate = true } - if !fileMgr.fileExistsAtPath(WhiteListDomainPACFilePath) && !fileMgr.fileExistsAtPath(WhiteListIPPACFilePath) { + if !fileMgr.fileExists(atPath: WhiteListDomainPACFilePath) && !fileMgr.fileExists(atPath: WhiteListIPPACFilePath) { needGenerate = true } if needGenerate { - GeneratePACFile() + let _ = GeneratePACFile() } } func GeneratePACFile() -> Bool { - let fileMgr = NSFileManager.defaultManager() + let fileMgr = FileManager.default // Maker the dir if rulesDirPath is not exesited. - if !fileMgr.fileExistsAtPath(PACRulesDirPath) { - if fileMgr.fileExistsAtPath(OldErrorPACRulesDirPath) { - try! fileMgr.moveItemAtPath(OldErrorPACRulesDirPath, toPath: PACRulesDirPath) + if !fileMgr.fileExists(atPath: PACRulesDirPath) { + if fileMgr.fileExists(atPath: OldErrorPACRulesDirPath) { + try! fileMgr.moveItem(atPath: OldErrorPACRulesDirPath, toPath: PACRulesDirPath) } else { - try! fileMgr.createDirectoryAtPath(PACRulesDirPath + try! fileMgr.createDirectory(atPath: PACRulesDirPath , withIntermediateDirectories: true, attributes: nil) } } // If gfwlist.txt is not exsited, copy from bundle - if !fileMgr.fileExistsAtPath(GFWListFilePath) { - let src = NSBundle.mainBundle().pathForResource("gfwlist", ofType: "txt") - try! fileMgr.copyItemAtPath(src!, toPath: GFWListFilePath) + if !fileMgr.fileExists(atPath: GFWListFilePath) { + let src = Bundle.main.path(forResource: "gfwlist", ofType: "txt") + try! fileMgr.copyItem(atPath: src!, toPath: GFWListFilePath) } // If user-rule.txt is not exsited, copy from bundle - if !fileMgr.fileExistsAtPath(PACUserRuleFilePath) { - let src = NSBundle.mainBundle().pathForResource("user-rule", ofType: "txt") - try! fileMgr.copyItemAtPath(src!, toPath: PACUserRuleFilePath) + if !fileMgr.fileExists(atPath: PACUserRuleFilePath) { + let src = Bundle.main.path(forResource: "user-rule", ofType: "txt") + try! fileMgr.copyItem(atPath: src!, toPath: PACUserRuleFilePath) } // If whitelist.pac is not exsited, copy from bundle - if !fileMgr.fileExistsAtPath(WhiteListDomainPACFilePath) { - let src = NSBundle.mainBundle().pathForResource("whitelist", ofType: "pac") - try! fileMgr.copyItemAtPath(src!, toPath: WhiteListDomainPACFilePath) + if !fileMgr.fileExists(atPath: WhiteListDomainPACFilePath) { + let src = Bundle.main.path(forResource: "whitelist", ofType: "pac") + try! fileMgr.copyItem(atPath: src!, toPath: WhiteListDomainPACFilePath) } // If whitelistip.pac is not exsited, copy from bundle - if !fileMgr.fileExistsAtPath(WhiteListIPPACFilePath) { - let src = NSBundle.mainBundle().pathForResource("whiteiplist", ofType: "pac") - try! fileMgr.copyItemAtPath(src!, toPath: WhiteListIPPACFilePath) + if !fileMgr.fileExists(atPath: WhiteListIPPACFilePath) { + let src = Bundle.main.path(forResource: "whiteiplist", ofType: "pac") + try! fileMgr.copyItem(atPath: src!, toPath: WhiteListIPPACFilePath) } - let socks5Port = NSUserDefaults.standardUserDefaults().integerForKey("LocalSocks5.ListenPort") + let socks5Port = UserDefaults.standard.integer(forKey: "LocalSocks5.ListenPort") do { - let gfwlist = try String(contentsOfFile: GFWListFilePath, encoding: NSUTF8StringEncoding) - if let data = NSData(base64EncodedString: gfwlist, options: .IgnoreUnknownCharacters) { - let str = String(data: data, encoding: NSUTF8StringEncoding) - var lines = str!.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) + let gfwlist = try String(contentsOfFile: GFWListFilePath, encoding: String.Encoding.utf8) + if let data = Data(base64Encoded: gfwlist, options: .ignoreUnknownCharacters) { + let str = String(data: data, encoding: String.Encoding.utf8) + var lines = str!.components(separatedBy: CharacterSet.newlines) do { - let userRuleStr = try String(contentsOfFile: PACUserRuleFilePath, encoding: NSUTF8StringEncoding) - let userRuleLines = userRuleStr.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) + let userRuleStr = try String(contentsOfFile: PACUserRuleFilePath, encoding: String.Encoding.utf8) + let userRuleLines = userRuleStr.components(separatedBy: CharacterSet.newlines) lines += userRuleLines } catch { @@ -112,51 +112,51 @@ func GeneratePACFile() -> Bool { do { // rule lines to json array - let rulesJsonData: NSData - = try NSJSONSerialization.dataWithJSONObject(lines, options: .PrettyPrinted) - let rulesJsonStr = String(data: rulesJsonData, encoding: NSUTF8StringEncoding) + let rulesJsonData: Data + = try JSONSerialization.data(withJSONObject: lines, options: .prettyPrinted) + let rulesJsonStr = String(data: rulesJsonData, encoding: String.Encoding.utf8) // Get raw pac js - let jsPath = NSBundle.mainBundle().URLForResource("abp", withExtension: "js") - let jsData = NSData(contentsOfURL: jsPath!) - var jsStr = String(data: jsData!, encoding: NSUTF8StringEncoding) + let jsPath = Bundle.main.url(forResource: "abp", withExtension: "js") + let jsData = try? Data(contentsOf: jsPath!) + var jsStr = String(data: jsData!, encoding: String.Encoding.utf8) // Replace rules placeholder in pac js - jsStr = jsStr!.stringByReplacingOccurrencesOfString("__RULES__" - , withString: rulesJsonStr!) + jsStr = jsStr!.replacingOccurrences(of: "__RULES__" + , with: rulesJsonStr!) // Replace __SOCKS5PORT__ palcholder in pac js - let result = jsStr!.stringByReplacingOccurrencesOfString("__SOCKS5PORT__" - , withString: "\(socks5Port)") + let result = jsStr!.replacingOccurrences(of: "__SOCKS5PORT__" + , with: "\(socks5Port)") // Write the pac js to file. - try result.dataUsingEncoding(NSUTF8StringEncoding)? - .writeToFile(PACFilePath, options: .DataWritingAtomic) + try result.data(using: String.Encoding.utf8)? + .write(to: URL(fileURLWithPath: PACFilePath), options: .atomic) // Setup Pac for White List - let DomainSrc = NSBundle.mainBundle().pathForResource("whitelist", ofType: "pac") - let IPSrc = NSBundle.mainBundle().pathForResource("whiteiplist", ofType: "pac") - let DomainPacFile = NSData(contentsOfFile: DomainSrc!) - let IPPACFile = NSData(contentsOfFile: IPSrc!) - var DomainPACStr = String(data: DomainPacFile!,encoding: NSUTF8StringEncoding)! - var IPPACStr = String(data: IPPACFile!,encoding: NSUTF8StringEncoding)! - if(DomainPACStr.rangeOfString("SOCKS ") == nil) { - DomainPACStr = DomainPACStr.stringByReplacingOccurrencesOfString("SOCKS5 127.0.0.1:1080;", withString: "SOCKS5 127.0.0.1:\(socks5Port);SOCKS 127.0.0.1:\(socks5Port);") + let DomainSrc = Bundle.main.path(forResource: "whitelist", ofType: "pac") + let IPSrc = Bundle.main.path(forResource: "whiteiplist", ofType: "pac") + let DomainPacFile = try? Data(contentsOf: URL(fileURLWithPath: DomainSrc!)) + let IPPACFile = try? Data(contentsOf: URL(fileURLWithPath: IPSrc!)) + var DomainPACStr = String(data: DomainPacFile!,encoding: String.Encoding.utf8)! + var IPPACStr = String(data: IPPACFile!,encoding: String.Encoding.utf8)! + if(DomainPACStr.range(of: "SOCKS ") == nil) { + DomainPACStr = DomainPACStr.replacingOccurrences(of: "SOCKS5 127.0.0.1:1080;", with: "SOCKS5 127.0.0.1:\(socks5Port);SOCKS 127.0.0.1:\(socks5Port);") }else{ - DomainPACStr = DomainPACStr.stringByReplacingOccurrencesOfString("SOCKS 127.0.0.1:1080;", withString: "SOCKS 127.0.0.1:\(socks5Port);") - DomainPACStr = DomainPACStr.stringByReplacingOccurrencesOfString("SOCKS5 127.0.0.1:1080;", withString: "SOCKS5 127.0.0.1:\(socks5Port);") + DomainPACStr = DomainPACStr.replacingOccurrences(of: "SOCKS 127.0.0.1:1080;", with: "SOCKS 127.0.0.1:\(socks5Port);") + DomainPACStr = DomainPACStr.replacingOccurrences(of: "SOCKS5 127.0.0.1:1080;", with: "SOCKS5 127.0.0.1:\(socks5Port);") } - if(IPPACStr.rangeOfString("SOCKS ") == nil) { - IPPACStr = IPPACStr.stringByReplacingOccurrencesOfString("SOCKS5 127.0.0.1:1080;", withString: "SOCKS5 127.0.0.1:\(socks5Port);SOCKS 127.0.0.1:\(socks5Port);") + if(IPPACStr.range(of: "SOCKS ") == nil) { + IPPACStr = IPPACStr.replacingOccurrences(of: "SOCKS5 127.0.0.1:1080;", with: "SOCKS5 127.0.0.1:\(socks5Port);SOCKS 127.0.0.1:\(socks5Port);") }else{ - IPPACStr = IPPACStr.stringByReplacingOccurrencesOfString("SOCKS 127.0.0.1:1080;", withString: "SOCKS 127.0.0.1:\(socks5Port);") - IPPACStr = IPPACStr.stringByReplacingOccurrencesOfString("SOCKS5 127.0.0.1:1080;", withString: "SOCKS5 127.0.0.1:\(socks5Port);") + IPPACStr = IPPACStr.replacingOccurrences(of: "SOCKS 127.0.0.1:1080;", with: "SOCKS 127.0.0.1:\(socks5Port);") + IPPACStr = IPPACStr.replacingOccurrences(of: "SOCKS5 127.0.0.1:1080;", with: "SOCKS5 127.0.0.1:\(socks5Port);") } try - DomainPACStr.dataUsingEncoding(NSUTF8StringEncoding)?.writeToFile(WhiteListDomainPACFilePath, options: .DataWritingAtomic) + DomainPACStr.data(using: String.Encoding.utf8)?.write(to: URL(fileURLWithPath: WhiteListDomainPACFilePath), options: .atomic) try - IPPACStr.dataUsingEncoding(NSUTF8StringEncoding)?.writeToFile(WhiteListIPPACFilePath, options: .DataWritingAtomic) + IPPACStr.data(using: String.Encoding.utf8)?.write(to: URL(fileURLWithPath: WhiteListIPPACFilePath), options: .atomic) return true } catch { @@ -172,28 +172,28 @@ func GeneratePACFile() -> Bool { func UpdatePACFromGFWList() { // Make the dir if rulesDirPath is not exesited. - if !NSFileManager.defaultManager().fileExistsAtPath(PACRulesDirPath) { + if !FileManager.default.fileExists(atPath: PACRulesDirPath) { do { - try NSFileManager.defaultManager().createDirectoryAtPath(PACRulesDirPath + try FileManager.default.createDirectory(atPath: PACRulesDirPath , withIntermediateDirectories: true, attributes: nil) } catch { } } - let url = NSUserDefaults.standardUserDefaults().stringForKey("GFWListURL") - Alamofire.request(.GET, url!) + let url = UserDefaults.standard.string(forKey: "GFWListURL") + Alamofire.request(url!) .responseString { response in if response.result.isSuccess { if let v = response.result.value { do { - try v.writeToFile(GFWListFilePath, atomically: true, encoding: NSUTF8StringEncoding) + try v.write(toFile: GFWListFilePath, atomically: true, encoding: String.Encoding.utf8) if GeneratePACFile() { // Popup a user notification let notification = NSUserNotification() notification.title = "PAC has been updated by latest GFW List.".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) } } catch { @@ -203,35 +203,35 @@ func UpdatePACFromGFWList() { // Popup a user notification let notification = NSUserNotification() notification.title = "Failed to download latest GFW List.".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) } } } func UpdatePACFromWhiteList(){ - if !NSFileManager.defaultManager().fileExistsAtPath(PACRulesDirPath) { + if !FileManager.default.fileExists(atPath: PACRulesDirPath) { do { - try NSFileManager.defaultManager().createDirectoryAtPath(PACRulesDirPath + try FileManager.default.createDirectory(atPath: PACRulesDirPath , withIntermediateDirectories: true, attributes: nil) } catch { } } - let url = NSUserDefaults.standardUserDefaults().stringForKey("WhiteListURL") - Alamofire.request(.GET, url!) + let url = UserDefaults.standard.string(forKey: "WhiteListURL") + Alamofire.request(url!)// request(.GET, url!) .responseString { response in if response.result.isSuccess { if let v = response.result.value { do { - try v.writeToFile(WhiteListDomainPACFilePath, atomically: true, encoding: NSUTF8StringEncoding) + try v.write(toFile: WhiteListDomainPACFilePath, atomically: true, encoding: String.Encoding.utf8) if GeneratePACFile() { // Popup a user notification let notification = NSUserNotification() notification.title = "White List update succeed.".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) } } catch { @@ -241,25 +241,25 @@ func UpdatePACFromWhiteList(){ // Popup a user notification let notification = NSUserNotification() notification.title = "Failed to download latest White List update succeed.".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) } } - let IPURL = NSUserDefaults.standardUserDefaults().stringForKey("WhiteListIPURL") - Alamofire.request(.GET, IPURL!) + let IPURL = UserDefaults.standard.string(forKey: "WhiteListIPURL") + Alamofire.request(IPURL!) .responseString { response in if response.result.isSuccess { if let v = response.result.value { do { - try v.writeToFile(WhiteListIPPACFilePath, atomically: true, encoding: NSUTF8StringEncoding) + try v.write(toFile:WhiteListIPPACFilePath, atomically: true, encoding: String.Encoding.utf8) if GeneratePACFile() { // Popup a user notification let notification = NSUserNotification() notification.title = "White List update succeed.".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) } } catch { @@ -269,8 +269,8 @@ func UpdatePACFromWhiteList(){ // Popup a user notification let notification = NSUserNotification() notification.title = "Failed to download latest White List update succeed.".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) } } } diff --git a/ShadowsocksX-NG/PingClient.swift b/ShadowsocksX-NG/PingClient.swift index 5318023..4ad6cb1 100644 --- a/ShadowsocksX-NG/PingClient.swift +++ b/ShadowsocksX-NG/PingClient.swift @@ -8,21 +8,32 @@ import Foundation +fileprivate func < (lhs: T?, rhs: T?) -> Bool { + switch (lhs, rhs) { + case let (l?, r?): + return l < r + case (nil, _?): + return true + default: + return false + } +} + public typealias SimplePingClientCallback = (String?)->() -public class SimplePingClient: NSObject { +open class SimplePingClient: NSObject { static let singletonPC = SimplePingClient() - private var resultCallback: SimplePingClientCallback? - private var pingClinet: SimplePing? - private var dateReference: NSDate? + fileprivate var resultCallback: SimplePingClientCallback? + fileprivate var pingClinet: SimplePing? + fileprivate var dateReference: Date? - public static func pingHostname(hostname: String, andResultCallback callback: SimplePingClientCallback?) { + open static func pingHostname(_ hostname: String, andResultCallback callback: SimplePingClientCallback?) { singletonPC.pingHostname(hostname, andResultCallback: callback) } - public func pingHostname(hostname: String, andResultCallback callback: SimplePingClientCallback?) { + open func pingHostname(_ hostname: String, andResultCallback callback: SimplePingClientCallback?) { resultCallback = callback pingClinet = SimplePing(hostName: hostname) pingClinet?.delegate = self @@ -31,37 +42,37 @@ public class SimplePingClient: NSObject { } extension SimplePingClient: SimplePingDelegate { - public func simplePing(pinger: SimplePing, didStartWithAddress address: NSData) { - pinger.sendPingWithData(nil) + public func simplePing(_ pinger: SimplePing, didStartWithAddress address: Data) { + pinger.send(with: nil) } - public func simplePing(pinger: SimplePing, didFailWithError error: NSError) { + @nonobjc public func simplePing(_ pinger: SimplePing, didFailWithError error: NSError) { resultCallback?(nil) } - public func simplePing(pinger: SimplePing, didSendPacket packet: NSData, sequenceNumber: UInt16) { - dateReference = NSDate() + public func simplePing(_ pinger: SimplePing, didSendPacket packet: Data, sequenceNumber: UInt16) { + dateReference = Date() } - public func simplePing(pinger: SimplePing, didFailToSendPacket packet: NSData, sequenceNumber: UInt16, error: NSError) { + @nonobjc public func simplePing(_ pinger: SimplePing, didFailToSendPacket packet: Data, sequenceNumber: UInt16, error: NSError) { pinger.stop() resultCallback?(nil) } - public func simplePing(pinger: SimplePing, didReceiveUnexpectedPacket packet: NSData) { + public func simplePing(_ pinger: SimplePing, didReceiveUnexpectedPacket packet: Data) { pinger.stop() resultCallback?(nil) } - public func simplePing(pinger: SimplePing, didReceivePingResponsePacket packet: NSData, sequenceNumber: UInt16 ){ + public func simplePing(_ pinger: SimplePing, didReceivePingResponsePacket packet: Data, sequenceNumber: UInt16 ){ pinger.stop() guard let dateReference = dateReference else{return } //timeIntervalSinceDate returns seconds, so we convert to milis - let latency = NSDate().timeIntervalSinceDate(dateReference) * 1000 + let latency = Date().timeIntervalSince(dateReference) * 1000 resultCallback?(String(format: "%.f", latency)) } } @@ -76,19 +87,19 @@ class PingServers:NSObject{ var fastest:String? var fastest_id : Int=0 - func ping(i:Int=0){ + func ping(_ i:Int=0){ if i == 0{ fastest_id = 0 fastest = nil } if i >= SerMgr.profiles.count{ - (NSApplication.sharedApplication().delegate as! AppDelegate).updateServersMenu() - (NSApplication.sharedApplication().delegate as! AppDelegate).updateRunningModeMenu() + (NSApplication.shared().delegate as! AppDelegate).updateServersMenu() + (NSApplication.shared().delegate as! AppDelegate).updateRunningModeMenu() let notice = NSUserNotification() notice.title = "Ping测试完成!" notice.subtitle = "最快的是\(SerMgr.profiles[fastest_id].remark) \(SerMgr.profiles[fastest_id].serverHost) \(SerMgr.profiles[fastest_id].latency!)ms" - NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notice) + NSUserNotificationCenter.default.deliver(notice) return } let host = SerMgr.profiles[i].serverHost diff --git a/ShadowsocksX-NG/PingTest.swift b/ShadowsocksX-NG/PingTest.swift index 75aa054..0c96240 100644 --- a/ShadowsocksX-NG/PingTest.swift +++ b/ShadowsocksX-NG/PingTest.swift @@ -14,8 +14,8 @@ class PingTest: NSObject, SimplePingDelegate { var hostName = "jp10.hexiehao.pw" var pinger: SimplePing? - var sendTimer: NSTimer? - var dateReference: NSDate? + var sendTimer: Timer? + var dateReference: Date? /// Called by the table view selection delegate callback to start the ping. init(hostName:String) { @@ -49,12 +49,12 @@ class PingTest: NSObject, SimplePingDelegate { /// via a timer (to continue sending pings periodically). func sendPing() { - self.pinger!.sendPingWithData(nil) + self.pinger!.send(with: nil) } // MARK: pinger delegate callback - func simplePing(pinger: SimplePing, didStartWithAddress address: NSData) { + func simplePing(_ pinger: SimplePing, didStartWithAddress address: Data) { NSLog("pinging %@",hostName) // Send the first ping straight away. @@ -64,45 +64,45 @@ class PingTest: NSObject, SimplePingDelegate { // And start a timer to send the subsequent pings. assert(self.sendTimer == nil) - self.sendTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(PingTest.sendPing), userInfo: nil, repeats: true) + self.sendTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(PingTest.sendPing), userInfo: nil, repeats: true) } - func simplePing(pinger: SimplePing, didFailWithError error: NSError) { - NSLog("failed: %@", PingTest.shortErrorFromError(error)) + func simplePing(_ pinger: SimplePing, didFailWithError error: Error) { + NSLog("failed: %@", PingTest.shortErrorFromError(error as NSError)) self.stop() } - func simplePing(pinger: SimplePing, didSendPacket packet: NSData, sequenceNumber: UInt16) { + func simplePing(_ pinger: SimplePing, didSendPacket packet: Data, sequenceNumber: UInt16) { NSLog("#%u sent", sequenceNumber) - dateReference = NSDate() + dateReference = Date() } - func simplePing(pinger: SimplePing, didFailToSendPacket packet: NSData, sequenceNumber: UInt16, error: NSError) { - NSLog("#%u send failed: %@", sequenceNumber, PingTest.shortErrorFromError(error)) + func simplePing(_ pinger: SimplePing, didFailToSendPacket packet: Data, sequenceNumber: UInt16, error: Error) { + NSLog("#%u send failed: %@", sequenceNumber, PingTest.shortErrorFromError(error as NSError)) } - func simplePing(pinger: SimplePing, didReceivePingResponsePacket packet: NSData, sequenceNumber: UInt16) { + func simplePing(_ pinger: SimplePing, didReceivePingResponsePacket packet: Data, sequenceNumber: UInt16) { pinger.stop() guard let dateReference = dateReference else { return } //timeIntervalSinceDate returns seconds, so we convert to milis - dispatch_async(dispatch_get_main_queue(), { - let latency = NSDate().timeIntervalSinceDate(dateReference) * 1000 - NSLog("#%u received, host=%@, size=%zu, latency=%.f", sequenceNumber, self.hostName , packet.length,latency) + DispatchQueue.main.async(execute: { + let latency = Date().timeIntervalSince(dateReference) * 1000 + NSLog("#%u received, host=%@, size=%zu, latency=%.f", sequenceNumber, self.hostName , packet.count,latency) let userNote = NSUserNotification() userNote.title = "\(self.hostName) ping \(latency)".localized userNote.subtitle = "Address can't not be recognized".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(userNote) + NSUserNotificationCenter.default + .deliver(userNote) }) } - func simplePing(pinger: SimplePing, didReceiveUnexpectedPacket packet: NSData) { - NSLog("unexpected packet, size=%zu", packet.length) + func simplePing(_ pinger: SimplePing, didReceiveUnexpectedPacket packet: Data) { + NSLog("unexpected packet, size=%zu", packet.count) } // MARK: utilities @@ -113,12 +113,12 @@ class PingTest: NSObject, SimplePingDelegate { /// /// - returns: A string representation of that address. - static func displayAddressForAddress(address: NSData) -> String { - var hostStr = [Int8](count: Int(NI_MAXHOST), repeatedValue: 0) + static func displayAddressForAddress(_ address: Data) -> String { + var hostStr = [Int8](repeating: 0, count: Int(NI_MAXHOST)) let success = getnameinfo( - UnsafePointer(address.bytes), - socklen_t(address.length), + (address as NSData).bytes.bindMemory(to: sockaddr.self, capacity: address.count), + socklen_t(address.count), &hostStr, socklen_t(hostStr.count), nil, @@ -127,7 +127,7 @@ class PingTest: NSObject, SimplePingDelegate { ) == 0 let result: String if success { - result = String.fromCString(hostStr)! + result = String(cString: hostStr) } else { result = "?" } @@ -140,14 +140,14 @@ class PingTest: NSObject, SimplePingDelegate { /// /// - returns: A short string representing that error. - static func shortErrorFromError(error: NSError) -> String { - if error.domain == kCFErrorDomainCFNetwork as String && error.code == Int(CFNetworkErrors.CFHostErrorUnknown.rawValue) { - if let failureObj = error.userInfo[kCFGetAddrInfoFailureKey] { + static func shortErrorFromError(_ error: NSError) -> String { + if error.domain == kCFErrorDomainCFNetwork as String && error.code == Int(CFNetworkErrors.cfHostErrorUnknown.rawValue) { + if let failureObj = error.userInfo[kCFGetAddrInfoFailureKey as AnyHashable] { if let failureNum = failureObj as? NSNumber { - if failureNum.intValue != 0 { - let f = gai_strerror(failureNum.intValue) + if failureNum.int32Value != 0 { + let f = gai_strerror(failureNum.int32Value) if f != nil { - return String.fromCString(f)! + return String(cString: f!) } } } diff --git a/ShadowsocksX-NG/PreferencesWindowController.swift b/ShadowsocksX-NG/PreferencesWindowController.swift index 12739fa..7d3d34a 100644 --- a/ShadowsocksX-NG/PreferencesWindowController.swift +++ b/ShadowsocksX-NG/PreferencesWindowController.swift @@ -35,7 +35,7 @@ class PreferencesWindowController: NSWindowController @IBOutlet weak var removeButton: NSButton! let tableViewDragType: String = "ss.server.profile.data" - var defaults: NSUserDefaults! + var defaults: UserDefaults! var profileMgr: ServerProfileManager! var editingProfile: ServerProfile! @@ -45,10 +45,10 @@ class PreferencesWindowController: NSWindowController super.windowDidLoad() // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. - defaults = NSUserDefaults.standardUserDefaults() + defaults = UserDefaults.standard profileMgr = ServerProfileManager.instance - methodTextField.addItemsWithObjectValues([ + methodTextField.addItems(withObjectValues: [ "table", "rc4", "rc4-md5-6", @@ -69,7 +69,7 @@ class PreferencesWindowController: NSWindowController "chacha20", "chacha20-ietf" ]) - ProtocolTextField.addItemsWithObjectValues([ + ProtocolTextField.addItems(withObjectValues: [ "origin", "verify_simple", "verify_sha1", @@ -77,7 +77,7 @@ class PreferencesWindowController: NSWindowController "auth_sha1_v2", "auth_sha1_v4", ]) - ObfsTextField.addItemsWithObjectValues([ + ObfsTextField.addItems(withObjectValues: [ "palin", "http_simple", "tls_simple", @@ -89,10 +89,10 @@ class PreferencesWindowController: NSWindowController } override func awakeFromNib() { - profilesTableView.registerForDraggedTypes([tableViewDragType]) + profilesTableView.register(forDraggedTypes: [tableViewDragType]) } - @IBAction func addProfile(sender: NSButton) { + @IBAction func addProfile(_ sender: NSButton) { if editingProfile != nil && !editingProfile.isValid(){ shakeWindows() return @@ -102,8 +102,8 @@ class PreferencesWindowController: NSWindowController profile.remark = "New Server".localized profileMgr.profiles.append(profile) - let index = NSIndexSet(index: profileMgr.profiles.count-1) - profilesTableView.insertRowsAtIndexes(index, withAnimation: .EffectFade) + let index = IndexSet(integer: profileMgr.profiles.count-1) + profilesTableView.insertRows(at: index, withAnimation: .effectFade) self.profilesTableView.scrollRowToVisible(self.profileMgr.profiles.count-1) self.profilesTableView.selectRowIndexes(index, byExtendingSelection: false) @@ -111,18 +111,18 @@ class PreferencesWindowController: NSWindowController updateProfileBoxVisible() } - @IBAction func removeProfile(sender: NSButton) { + @IBAction func removeProfile(_ sender: NSButton) { let index = profilesTableView.selectedRow if index >= 0 { profilesTableView.beginUpdates() - profileMgr.profiles.removeAtIndex(index) - profilesTableView.removeRowsAtIndexes(NSIndexSet(index: index), withAnimation: .EffectFade) + profileMgr.profiles.remove(at: index) + profilesTableView.removeRows(at: IndexSet(integer: index), withAnimation: .effectFade) profilesTableView.endUpdates() } updateProfileBoxVisible() } - @IBAction func ok(sender: NSButton) { + @IBAction func ok(_ sender: NSButton) { if editingProfile != nil { if !editingProfile.isValid() { // Done Shake window @@ -134,15 +134,15 @@ class PreferencesWindowController: NSWindowController window?.performClose(nil) - NSNotificationCenter.defaultCenter() - .postNotificationName(NOTIFY_SERVER_PROFILES_CHANGED, object: nil) + NotificationCenter.default + .post(name: Notification.Name(rawValue: NOTIFY_SERVER_PROFILES_CHANGED), object: nil) } - @IBAction func cancel(sender: NSButton) { + @IBAction func cancel(_ sender: NSButton) { window?.performClose(self) } - @IBAction func duplicateProfile(sender: NSButton) { + @IBAction func duplicateProfile(_ sender: NSButton) { //读取当前profile,并且保存 if editingProfile != nil && !editingProfile.isValid(){ return @@ -156,27 +156,27 @@ class PreferencesWindowController: NSWindowController newProfile = ServerProfile.fromDictionary(oldProfile.toDictionary())//here 因为UUID重复了 newProfile.uuid = newUUID profileMgr.profiles.append(newProfile) - let index = NSIndexSet(index: profileMgr.profiles.count-1) - profilesTableView.insertRowsAtIndexes(index, withAnimation: .EffectFade) + let index = IndexSet(integer: profileMgr.profiles.count-1) + profilesTableView.insertRows(at: index, withAnimation: .effectFade) self.profilesTableView.scrollRowToVisible(self.profileMgr.profiles.count-1) self.profilesTableView.selectRowIndexes(index, byExtendingSelection: false) profilesTableView.endUpdates() updateProfileBoxVisible() - NSNotificationCenter.defaultCenter() - .postNotificationName(NOTIFY_SERVER_PROFILES_CHANGED, object: nil) + NotificationCenter.default + .post(name: Notification.Name(rawValue: NOTIFY_SERVER_PROFILES_CHANGED), object: nil) } } - @IBAction func copyCurrentProfileURL2Pasteboard(sender: NSButton) { + @IBAction func copyCurrentProfileURL2Pasteboard(_ sender: NSButton) { let index = profilesTableView.selectedRow if index >= 0 { let profile = profileMgr.profiles[index] let ssURL = profile.URL() if let url = ssURL { - let pboard = NSPasteboard.generalPasteboard() + let pboard = NSPasteboard.general() pboard.clearContents() - let rs = pboard.setString(String(url), forType: NSStringPboardType)//writeObjects([url]) + let rs = pboard.setString(String(describing: url), forType: NSStringPboardType)//writeObjects([url]) if rs { NSLog("copy to pasteboard success") } else { @@ -188,45 +188,45 @@ class PreferencesWindowController: NSWindowController func updateProfileBoxVisible() { if profileMgr.profiles.count <= 1 { - removeButton.enabled = false + removeButton.isEnabled = false }else{ - removeButton.enabled = true + removeButton.isEnabled = true } if profileMgr.profiles.isEmpty { - profileBox.hidden = true + profileBox.isHidden = true } else { - profileBox.hidden = false + profileBox.isHidden = false } } - func bindProfile(index:Int) { + func bindProfile(_ index:Int) { NSLog("bind profile \(index)") if index >= 0 && index < profileMgr.profiles.count { editingProfile = profileMgr.profiles[index] - hostTextField.bind("value", toObject: editingProfile, withKeyPath: "serverHost" + hostTextField.bind("value", to: editingProfile, withKeyPath: "serverHost" , options: [NSContinuouslyUpdatesValueBindingOption: true]) - portTextField.bind("value", toObject: editingProfile, withKeyPath: "serverPort" + portTextField.bind("value", to: editingProfile, withKeyPath: "serverPort" , options: [NSContinuouslyUpdatesValueBindingOption: true]) - methodTextField.bind("value", toObject: editingProfile, withKeyPath: "method" + methodTextField.bind("value", to: editingProfile, withKeyPath: "method" , options: [NSContinuouslyUpdatesValueBindingOption: true]) - passwordTextField.bind("value", toObject: editingProfile, withKeyPath: "password" + passwordTextField.bind("value", to: editingProfile, withKeyPath: "password" , options: [NSContinuouslyUpdatesValueBindingOption: true]) - remarkTextField.bind("value", toObject: editingProfile, withKeyPath: "remark" + remarkTextField.bind("value", to: editingProfile, withKeyPath: "remark" , options: [NSContinuouslyUpdatesValueBindingOption: true]) - ProtocolTextField.bind("value", toObject: editingProfile, withKeyPath: "ssrProtocol", options: [NSContinuouslyUpdatesValueBindingOption: true]) + ProtocolTextField.bind("value", to: editingProfile, withKeyPath: "ssrProtocol", options: [NSContinuouslyUpdatesValueBindingOption: true]) - ProtocolParamTextField.bind("value", toObject: editingProfile, withKeyPath: "ssrProtocolParam", options: [NSContinuouslyUpdatesValueBindingOption: true]) + ProtocolParamTextField.bind("value", to: editingProfile, withKeyPath: "ssrProtocolParam", options: [NSContinuouslyUpdatesValueBindingOption: true]) - ObfsTextField.bind("value", toObject: editingProfile, withKeyPath: "ssrObfs", options: [NSContinuouslyUpdatesValueBindingOption: true]) + ObfsTextField.bind("value", to: editingProfile, withKeyPath: "ssrObfs", options: [NSContinuouslyUpdatesValueBindingOption: true]) - ObfsParamTextField.bind("value", toObject: editingProfile, withKeyPath: "ssrObfsParam", options: [NSContinuouslyUpdatesValueBindingOption: true]) + ObfsParamTextField.bind("value", to: editingProfile, withKeyPath: "ssrObfsParam", options: [NSContinuouslyUpdatesValueBindingOption: true]) - otaCheckBoxBtn.bind("value", toObject: editingProfile, withKeyPath: "ota" + otaCheckBoxBtn.bind("value", to: editingProfile, withKeyPath: "ota" , options: [NSContinuouslyUpdatesValueBindingOption: true]) } else { editingProfile = nil @@ -247,7 +247,7 @@ class PreferencesWindowController: NSWindowController } } - func getDataAtRow(index:Int) -> (String, Bool) { + func getDataAtRow(_ index:Int) -> (String, Bool) { let profile = profileMgr.profiles[index] let isActive = (profileMgr.activeProfileId == profile.uuid) if !profile.remark.isEmpty { @@ -260,16 +260,16 @@ class PreferencesWindowController: NSWindowController //-------------------------------------------------- // For NSTableViewDataSource - func numberOfRowsInTableView(tableView: NSTableView) -> Int { + func numberOfRows(in tableView: NSTableView) -> Int { if let mgr = profileMgr { return mgr.profiles.count } return 0 } - func tableView(tableView: NSTableView - , objectValueForTableColumn tableColumn: NSTableColumn? - , row: Int) -> AnyObject? { + func tableView(_ tableView: NSTableView + , objectValueFor tableColumn: NSTableColumn? + , row: Int) -> Any? { let (title, isActive) = getDataAtRow(row) @@ -287,26 +287,26 @@ class PreferencesWindowController: NSWindowController // Drag & Drop reorder rows - func tableView(tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? { + func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? { let item = NSPasteboardItem() item.setString(String(row), forType: tableViewDragType) return item } - func tableView(tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int + func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int , proposedDropOperation dropOperation: NSTableViewDropOperation) -> NSDragOperation { - if dropOperation == .Above { - return .Move + if dropOperation == .above { + return .move } - return .None + return NSDragOperation() } - func tableView(tableView: NSTableView, acceptDrop info: NSDraggingInfo + func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo , row: Int, dropOperation: NSTableViewDropOperation) -> Bool { if let mgr = profileMgr { var oldIndexes = [Int]() - info.enumerateDraggingItemsWithOptions([], forView: tableView, classes: [NSPasteboardItem.self], searchOptions: [:]) { - if let str = ($0.0.item as! NSPasteboardItem).stringForType(self.tableViewDragType), index = Int(str) { + 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) { oldIndexes.append(index) } } @@ -319,14 +319,14 @@ class PreferencesWindowController: NSWindowController tableView.beginUpdates() for oldIndex in oldIndexes { if oldIndex < row { - let o = mgr.profiles.removeAtIndex(oldIndex + oldIndexOffset) - mgr.profiles.insert(o, atIndex:row - 1) - tableView.moveRowAtIndex(oldIndex + oldIndexOffset, toIndex: row - 1) + let o = mgr.profiles.remove(at: oldIndex + oldIndexOffset) + mgr.profiles.insert(o, at:row - 1) + tableView.moveRow(at: oldIndex + oldIndexOffset, to: row - 1) oldIndexOffset -= 1 } else { - let o = mgr.profiles.removeAtIndex(oldIndex) - mgr.profiles.insert(o, atIndex:row + newIndexOffset) - tableView.moveRowAtIndex(oldIndex, toIndex: row + newIndexOffset) + let o = mgr.profiles.remove(at: oldIndex) + mgr.profiles.insert(o, at:row + newIndexOffset) + tableView.moveRow(at: oldIndex, to: row + newIndexOffset) newIndexOffset += 1 } } @@ -340,12 +340,12 @@ class PreferencesWindowController: NSWindowController //-------------------------------------------------- // For NSTableViewDelegate - func tableView(tableView: NSTableView - , shouldEditTableColumn tableColumn: NSTableColumn?, row: Int) -> Bool { + func tableView(_ tableView: NSTableView + , shouldEdit tableColumn: NSTableColumn?, row: Int) -> Bool { return false } - func tableView(tableView: NSTableView, shouldSelectRow row: Int) -> Bool { + func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { if row < 0 { editingProfile = nil return true @@ -359,12 +359,12 @@ class PreferencesWindowController: NSWindowController return true } - func tableViewSelectionDidChange(notification: NSNotification) { + func tableViewSelectionDidChange(_ notification: Notification) { if profilesTableView.selectedRow >= 0 { bindProfile(profilesTableView.selectedRow) } else { if !profileMgr.profiles.isEmpty { - let index = NSIndexSet(index: profileMgr.profiles.count - 1) + let index = IndexSet(integer: profileMgr.profiles.count - 1) profilesTableView.selectRowIndexes(index, byExtendingSelection: false) } } @@ -378,15 +378,18 @@ class PreferencesWindowController: NSWindowController let frame:CGRect = (window?.frame)! let shakeAnimation = CAKeyframeAnimation() - let shakePath = CGPathCreateMutable() - CGPathMoveToPoint(shakePath, nil, NSMinX(frame), NSMinY(frame)) + let shakePath = CGMutablePath() + shakePath.move(to: CGPoint.init(x: NSMinX(frame), y: NSMinY(frame)), transform: CGAffineTransform.init()) +// CGPathMoveToPoint(shakePath, nil, NSMinX(frame), NSMinY(frame)) for _ in 1...numberOfShakes{ - CGPathAddLineToPoint(shakePath, nil, NSMinX(frame) - frame.size.width * CGFloat(vigourOfShake), NSMinY(frame)) - CGPathAddLineToPoint(shakePath, nil, NSMinX(frame) + frame.size.width * CGFloat(vigourOfShake), NSMinY(frame)) + shakePath.addLine(to: CGPoint.init(x: NSMinX(frame) - frame.size.width * CGFloat(vigourOfShake), y: NSMinY(frame))) + shakePath.addLine(to: CGPoint.init(x: NSMinX(frame) + frame.size.width * CGFloat(vigourOfShake), y: NSMinY(frame))) +// CGPathAddLineToPoint(shakePath, nil, NSMinX(frame) - frame.size.width * CGFloat(vigourOfShake), NSMinY(frame)) +// CGPathAddLineToPoint(shakePath, nil, NSMinX(frame) + frame.size.width * CGFloat(vigourOfShake), NSMinY(frame)) } - CGPathCloseSubpath(shakePath) + shakePath.closeSubpath() shakeAnimation.path = shakePath shakeAnimation.duration = CFTimeInterval(durationOfShake) window?.animations = ["frameOrigin":shakeAnimation] diff --git a/ShadowsocksX-NG/ProxyPreferencesController.swift b/ShadowsocksX-NG/ProxyPreferencesController.swift index a28f787..5a6e3fc 100644 --- a/ShadowsocksX-NG/ProxyPreferencesController.swift +++ b/ShadowsocksX-NG/ProxyPreferencesController.swift @@ -23,71 +23,71 @@ class ProxyPreferencesController: NSWindowController, NSTableViewDataSource, NST super.windowDidLoad() // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. - let defaults = NSUserDefaults.standardUserDefaults() - self.setValue(defaults.boolForKey("AutoConfigureNetworkServices"), forKey: "autoConfigureNetworkServices") + let defaults = UserDefaults.standard + self.setValue(defaults.bool(forKey: "AutoConfigureNetworkServices"), forKey: "autoConfigureNetworkServices") - if let services = defaults.arrayForKey("Proxy4NetworkServices") { + if let services = defaults.array(forKey: "Proxy4NetworkServices") { selectedNetworkServices = NSMutableSet(array: services) } else { selectedNetworkServices = NSMutableSet() } - networkServices = ProxyConfTool.networkServicesList() + networkServices = ProxyConfTool.networkServicesList() as NSArray! tableView.reloadData() } - @IBAction func ok(sender: NSObject){ + @IBAction func ok(_ sender: NSObject){ ProxyConfHelper.disableProxy("hi") - let defaults = NSUserDefaults.standardUserDefaults() + let defaults = UserDefaults.standard defaults.setValue(selectedNetworkServices.allObjects, forKeyPath: "Proxy4NetworkServices") - defaults.setBool(autoConfigureNetworkServices, forKey: "AutoConfigureNetworkServices") + defaults.set(autoConfigureNetworkServices, forKey: "AutoConfigureNetworkServices") defaults.synchronize() window?.performClose(self) - NSNotificationCenter.defaultCenter() - .postNotificationName(NOTIFY_ADV_PROXY_CONF_CHANGED, object: nil) + NotificationCenter.default + .post(name: Notification.Name(rawValue: NOTIFY_ADV_PROXY_CONF_CHANGED), object: nil) } - @IBAction func cancel(sender: NSObject){ + @IBAction func cancel(_ sender: NSObject){ window?.performClose(self) } //-------------------------------------------------- // For NSTableViewDataSource - func numberOfRowsInTableView(tableView: NSTableView) -> Int { + func numberOfRows(in tableView: NSTableView) -> Int { if networkServices != nil { return networkServices.count } return 0; } - func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn? - , row: Int) -> AnyObject? { + func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn? + , row: Int) -> Any? { let cell = tableColumn!.dataCell as! NSButtonCell - let key = networkServices[row]["key"] as! String - if selectedNetworkServices.containsObject(key) { + let key = (networkServices[row] as AnyObject)["key"] as! String + if selectedNetworkServices.contains(key) { cell.state = 1 } else { cell.state = 0 } - let userDefinedName = networkServices[row]["userDefinedName"] as! String + let userDefinedName = (networkServices[row] as AnyObject)["userDefinedName"] as! String cell.title = userDefinedName return cell } - func tableView(tableView: NSTableView, setObjectValue object: AnyObject? - , forTableColumn tableColumn: NSTableColumn?, row: Int) { - let key = networkServices[row]["key"] as! String + func tableView(_ tableView: NSTableView, setObjectValue object: Any? + , for tableColumn: NSTableColumn?, row: Int) { + let key = (networkServices[row] as AnyObject)["key"] as! String // NSLog("%d", object!.integerValue) - if object!.integerValue == 1 { - selectedNetworkServices.addObject(key) + if (object! as AnyObject).intValue == 1 { + selectedNetworkServices.add(key) } else { - selectedNetworkServices.removeObject(key) + selectedNetworkServices.remove(key) } } } diff --git a/ShadowsocksX-NG/ServerProfile.swift b/ShadowsocksX-NG/ServerProfile.swift index 9f87dc7..cbd396b 100644 --- a/ShadowsocksX-NG/ServerProfile.swift +++ b/ShadowsocksX-NG/ServerProfile.swift @@ -28,18 +28,18 @@ class ServerProfile: NSObject { var latency:String? override init() { - uuid = NSUUID().UUIDString + uuid = UUID().uuidString } init(uuid: String) { self.uuid = uuid } - static func fromDictionary(data:[String:AnyObject]) -> ServerProfile { + static func fromDictionary(_ data:[String:AnyObject]) -> ServerProfile { let cp = { (profile: ServerProfile) in profile.serverHost = data["ServerHost"] as! String - profile.serverPort = (data["ServerPort"] as! NSNumber).unsignedShortValue + profile.serverPort = (data["ServerPort"] as! NSNumber).uint16Value profile.method = data["Method"] as! String profile.password = data["Password"] as! String @@ -76,43 +76,43 @@ class ServerProfile: NSObject { func toDictionary() -> [String:AnyObject] { var d = [String:AnyObject]() - d["Id"] = uuid - d["ServerHost"] = serverHost - d["ServerPort"] = NSNumber(unsignedShort:serverPort) - d["Method"] = method - d["Password"] = password - d["Remark"] = remark - d["OTA"] = ota - d["ssrProtocol"] = ssrProtocol - d["ssrProtocolParam"] = ssrProtocolParam - d["ssrObfs"] = ssrObfs - d["ssrObfsParam"] = ssrObfsParam + d["Id"] = uuid as AnyObject? + d["ServerHost"] = serverHost as AnyObject? + d["ServerPort"] = NSNumber(value: serverPort as UInt16) + d["Method"] = method as AnyObject? + d["Password"] = password as AnyObject? + d["Remark"] = remark as AnyObject? + d["OTA"] = ota as AnyObject? + d["ssrProtocol"] = ssrProtocol as AnyObject? + d["ssrProtocolParam"] = ssrProtocolParam as AnyObject? + d["ssrObfs"] = ssrObfs as AnyObject? + d["ssrObfsParam"] = ssrObfsParam as AnyObject? return d } func toJsonConfig() -> [String: AnyObject] { - var conf: [String: AnyObject] = ["server": serverHost, - "server_port": NSNumber(unsignedShort: serverPort), - "password": password, - "method": method,] + var conf: [String: AnyObject] = ["server": serverHost as AnyObject, + "server_port": NSNumber(value: serverPort as UInt16), + "password": password as AnyObject, + "method": method as AnyObject,] - let defaults = NSUserDefaults.standardUserDefaults() - conf["local_port"] = NSNumber(unsignedShort: UInt16(defaults.integerForKey("LocalSocks5.ListenPort"))) - conf["local_address"] = defaults.stringForKey("LocalSocks5.ListenAddress") - conf["timeout"] = NSNumber(unsignedInt: UInt32(defaults.integerForKey("LocalSocks5.Timeout"))) - conf["auth"] = NSNumber(bool: ota) + let defaults = UserDefaults.standard + conf["local_port"] = NSNumber(value: UInt16(defaults.integer(forKey: "LocalSocks5.ListenPort")) as UInt16) + conf["local_address"] = defaults.string(forKey: "LocalSocks5.ListenAddress") as AnyObject? + conf["timeout"] = NSNumber(value: UInt32(defaults.integer(forKey: "LocalSocks5.Timeout")) as UInt32) + conf["auth"] = NSNumber(value: ota as Bool) if(!ssrObfs.isEmpty){ - conf["protocol"] = ssrProtocol - conf["protocol_param"] = ssrProtocolParam - conf["obfs"] = ssrObfs - conf["obfs_param"] = ssrObfsParam + conf["protocol"] = ssrProtocol as AnyObject? + conf["protocol_param"] = ssrProtocolParam as AnyObject? + conf["obfs"] = ssrObfs as AnyObject? + conf["obfs_param"] = ssrObfsParam as AnyObject? } return conf } func isValid() -> Bool { - func validateIpAddress(ipToValidate: String) -> Bool { + func validateIpAddress(_ ipToValidate: String) -> Bool { var sin = sockaddr_in() var sin6 = sockaddr_in6() @@ -129,10 +129,10 @@ class ServerProfile: NSObject { return false; } - func validateDomainName(value: String) -> Bool { + func validateDomainName(_ value: String) -> Bool { let validHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$" - if (value.rangeOfString(validHostnameRegex, options: .RegularExpressionSearch) != nil) { + if (value.range(of: validHostnameRegex, options: .regularExpression) != nil) { return true } else { return false @@ -154,32 +154,32 @@ class ServerProfile: NSObject { return true } - func URL() -> NSURL? { + func URL() -> Foundation.URL? { if(ssrObfs=="plain"){ let parts = "\(method):\(password)@\(serverHost):\(serverPort)" - let base64String = parts.dataUsingEncoding(NSUTF8StringEncoding)? - .base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) + let base64String = parts.data(using: String.Encoding.utf8)? + .base64EncodedString(options: NSData.Base64EncodingOptions()) if var s = base64String { - s = s.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "=")) - return NSURL(string: "ss://\(s)") + s = s.trimmingCharacters(in: CharacterSet(charactersIn: "=")) + return Foundation.URL(string: "ss://\(s)") } }else{ let firstParts = "\(serverHost):\(serverPort):\(ssrProtocol):\(method):\(ssrObfs):" let secondParts = "\(password)" //base64(abc.xyz:12345:auth_sha1_v2:rc4-md5:tls1.2_ticket_auth:{base64(password)}/?obfsparam={base64(混淆参数(网址))}&remarks={base64(节点名称)}) - let base64PasswordString = secondParts.dataUsingEncoding(NSUTF8StringEncoding)? - .base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) + let base64PasswordString = secondParts.data(using: String.Encoding.utf8)? + .base64EncodedString(options: NSData.Base64EncodingOptions()) - let base64ssrObfsParamString = ssrObfsParam.dataUsingEncoding(NSUTF8StringEncoding)? - .base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) + let base64ssrObfsParamString = ssrObfsParam.data(using: String.Encoding.utf8)? + .base64EncodedString(options: NSData.Base64EncodingOptions()) - let base64RemarkString = remark.dataUsingEncoding(NSUTF8StringEncoding)? - .base64EncodedStringWithOptions(NSDataBase64EncodingOptions()) + let base64RemarkString = remark.data(using: String.Encoding.utf8)? + .base64EncodedString(options: NSData.Base64EncodingOptions()) var s = firstParts + base64PasswordString! + "/?" + "obfsparam=" + base64ssrObfsParamString! + "&remarks=" + base64RemarkString! - s = (s.dataUsingEncoding(NSUTF8StringEncoding)? - .base64EncodedStringWithOptions(NSDataBase64EncodingOptions()))! - return NSURL(string: "ssr://\(s)") + s = (s.data(using: String.Encoding.utf8)? + .base64EncodedString(options: NSData.Base64EncodingOptions()))! + return Foundation.URL(string: "ssr://\(s)") } return nil } diff --git a/ShadowsocksX-NG/ServerProfileManager.swift b/ShadowsocksX-NG/ServerProfileManager.swift index 95d52cc..e979d7a 100644 --- a/ShadowsocksX-NG/ServerProfileManager.swift +++ b/ShadowsocksX-NG/ServerProfileManager.swift @@ -15,45 +15,45 @@ class ServerProfileManager: NSObject { var profiles:[ServerProfile] var activeProfileId: String? - private override init() { + fileprivate override init() { profiles = [ServerProfile]() - let defaults = NSUserDefaults.standardUserDefaults() - if let _profiles = defaults.arrayForKey("ServerProfiles") { + let defaults = UserDefaults.standard + if let _profiles = defaults.array(forKey: "ServerProfiles") { for _profile in _profiles { let profile = ServerProfile.fromDictionary(_profile as! [String : AnyObject]) profiles.append(profile) } } - activeProfileId = defaults.stringForKey("ActiveServerProfileId") + activeProfileId = defaults.string(forKey: "ActiveServerProfileId") } - func setActiveProfiledId(id: String) { + func setActiveProfiledId(_ id: String) { activeProfileId = id - let defaults = NSUserDefaults.standardUserDefaults() - defaults.setObject(id, forKey: "ActiveServerProfileId") + let defaults = UserDefaults.standard + defaults.set(id, forKey: "ActiveServerProfileId") } func save() { - let defaults = NSUserDefaults.standardUserDefaults() + let defaults = UserDefaults.standard var _profiles = [AnyObject]() for profile in profiles { if profile.isValid() { let _profile = profile.toDictionary() - _profiles.append(_profile) + _profiles.append(_profile as AnyObject) } } - defaults.setObject(_profiles, forKey: "ServerProfiles") + defaults.set(_profiles, forKey: "ServerProfiles") if getActiveProfile() == nil { activeProfileId = nil } if activeProfileId != nil { - defaults.setObject(activeProfileId, forKey: "ActiveServerProfileId") - writeSSLocalConfFile((getActiveProfile()?.toJsonConfig())!) + defaults.set(activeProfileId, forKey: "ActiveServerProfileId") + let _ = writeSSLocalConfFile((getActiveProfile()?.toJsonConfig())!) } else { - defaults.removeObjectForKey("ActiveServerProfileId") + defaults.removeObject(forKey: "ActiveServerProfileId") removeSSLocalConfFile() } } @@ -78,22 +78,22 @@ class ServerProfileManager: NSObject { openPanel.canChooseDirectories = false openPanel.canCreateDirectories = false openPanel.canChooseFiles = true - openPanel.becomeKeyWindow() - openPanel.beginWithCompletionHandler { (result) -> Void in - if (result == NSFileHandlingPanelOKButton && (openPanel.URL) != nil) { - let fileManager = NSFileManager.defaultManager() - let filePath:String = (openPanel.URL?.path!)! - if (fileManager.fileExistsAtPath(filePath) && filePath.hasSuffix("json")) { - let data = fileManager.contentsAtPath(filePath) - let readString = NSString(data: data!, encoding: NSUTF8StringEncoding)! - let readStringData = readString.dataUsingEncoding(NSUTF8StringEncoding) + openPanel.becomeKey() + openPanel.begin { (result) -> Void in + if (result == NSFileHandlingPanelOKButton && (openPanel.url) != nil) { + let fileManager = FileManager.default + let filePath:String = (openPanel.url?.path)! + if (fileManager.fileExists(atPath: filePath) && filePath.hasSuffix("json")) { + let data = fileManager.contents(atPath: filePath) + let readString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)! + let readStringData = readString.data(using: String.Encoding.utf8.rawValue) - let jsonArr1 = try! NSJSONSerialization.JSONObjectWithData(readStringData!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary + let jsonArr1 = try! JSONSerialization.jsonObject(with: readStringData!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary - for item in jsonArr1.objectForKey("configs") as! [[String: AnyObject]]{ + for item in jsonArr1.object(forKey: "configs") as! [[String: AnyObject]]{ let profile = ServerProfile() profile.serverHost = item["server"] as! String - profile.serverPort = UInt16((item["server_port"]?.integerValue)!) + profile.serverPort = UInt16((item["server_port"] as! Int)) profile.method = item["method"] as! String profile.password = item["password"] as! String profile.remark = item["remarks"] as! String @@ -109,20 +109,20 @@ class ServerProfileManager: NSObject { } self.profiles.append(profile) self.save() - NSNotificationCenter.defaultCenter().postNotificationName(NOTIFY_SERVER_PROFILES_CHANGED, object: nil) + NotificationCenter.default.post(name: Notification.Name(rawValue: NOTIFY_SERVER_PROFILES_CHANGED), object: nil) } - let configsCount = jsonArr1.objectForKey("configs")?.count + let configsCount = (jsonArr1.object(forKey: "configs") as AnyObject).count let notification = NSUserNotification() notification.title = "Import Server Profile succeed!".localized notification.informativeText = "Successful import \(configsCount!) items".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) }else{ let notification = NSUserNotification() notification.title = "Import Server Profile failed!".localized notification.informativeText = "Invalid config file!".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) return } } @@ -131,13 +131,13 @@ class ServerProfileManager: NSObject { func exportConfigFile() { //读取example文件,删掉configs里面的配置,再用NSDictionary填充到configs里面 - let fileManager = NSFileManager.defaultManager() + let fileManager = FileManager.default - let filePath:String = NSBundle.mainBundle().bundlePath + "/Contents/Resources/example-gui-config.json" - let data = fileManager.contentsAtPath(filePath) - let readString = NSString(data: data!, encoding: NSUTF8StringEncoding)! - let readStringData = readString.dataUsingEncoding(NSUTF8StringEncoding) - let jsonArr1 = try! NSJSONSerialization.JSONObjectWithData(readStringData!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary + let filePath:String = Bundle.main.bundlePath + "/Contents/Resources/example-gui-config.json" + let data = fileManager.contents(atPath: filePath) + let readString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)! + let readStringData = readString.data(using: String.Encoding.utf8.rawValue) + let jsonArr1 = try! JSONSerialization.jsonObject(with: readStringData!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary let configsArray:NSMutableArray = [] //not using var? @@ -146,11 +146,11 @@ class ServerProfileManager: NSObject { //standard ss profile configProfile.setValue(true, forKey: "enable") configProfile.setValue(profile.serverHost, forKey: "server") - configProfile.setValue(NSNumber(unsignedShort:profile.serverPort), forKey: "server_port")//not work + configProfile.setValue(NSNumber(value: profile.serverPort as UInt16), forKey: "server_port")//not work configProfile.setValue(profile.password, forKey: "password") configProfile.setValue(profile.method, forKey: "method") configProfile.setValue(profile.remark, forKey: "remarks") - configProfile.setValue(profile.remark.dataUsingEncoding(NSUTF8StringEncoding)?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)), forKey: "remarks_base64") + configProfile.setValue(profile.remark.data(using: String.Encoding.utf8)?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)), forKey: "remarks_base64") //ssr if profile.ssrObfs != "" { configProfile.setValue(profile.ssrObfs, forKey: "obfs") @@ -162,43 +162,43 @@ class ServerProfileManager: NSObject { configProfile.setValue(profile.ssrProtocolParam, forKey: "protoclparam") } } - configsArray.addObject(configProfile) + configsArray.add(configProfile) } jsonArr1.setValue(configsArray, forKey: "configs") - let jsonData = try! NSJSONSerialization.dataWithJSONObject(jsonArr1, options: NSJSONWritingOptions.PrettyPrinted) - let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String + let jsonData = try! JSONSerialization.data(withJSONObject: jsonArr1, options: JSONSerialization.WritingOptions.prettyPrinted) + let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String let savePanel = NSSavePanel() savePanel.title = "Export Config Json File".localized savePanel.canCreateDirectories = true savePanel.allowedFileTypes = ["json"] savePanel.nameFieldStringValue = "export.json" - savePanel.becomeKeyWindow() - savePanel.beginWithCompletionHandler { (result) -> Void in - if (result == NSFileHandlingPanelOKButton && (savePanel.URL) != nil) { + savePanel.becomeKey() + savePanel.begin { (result) -> Void in + if (result == NSFileHandlingPanelOKButton && (savePanel.url) != nil) { //write jsonArr1 back to file - try! jsonString.writeToFile((savePanel.URL?.path)!, atomically: true, encoding: NSUTF8StringEncoding) - NSWorkspace.sharedWorkspace().selectFile((savePanel.URL?.path)!, inFileViewerRootedAtPath: (savePanel.directoryURL?.path)!) + try! jsonString.write(toFile: (savePanel.url?.path)!, atomically: true, encoding: String.Encoding.utf8) + 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 - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) } } } class func showExampleConfigFile() { //copy file to ~/Downloads folder - let filePath:String = NSBundle.mainBundle().bundlePath + "/Contents/Resources/example-gui-config.json" - let fileMgr = NSFileManager.defaultManager() + let filePath:String = Bundle.main.bundlePath + "/Contents/Resources/example-gui-config.json" + let fileMgr = FileManager.default let dataPath = NSHomeDirectory() + "/Downloads" let destPath = dataPath + "/example-gui-config.json" //检测文件是否已经存在,如果存在直接用sharedWorkspace显示 - if fileMgr.fileExistsAtPath(destPath) { - NSWorkspace.sharedWorkspace().selectFile(destPath, inFileViewerRootedAtPath: dataPath) + if fileMgr.fileExists(atPath: destPath) { + NSWorkspace.shared().selectFile(destPath, inFileViewerRootedAtPath: dataPath) }else{ - try! fileMgr.copyItemAtPath(filePath, toPath: destPath) - NSWorkspace.sharedWorkspace().selectFile(destPath, inFileViewerRootedAtPath: dataPath) + try! fileMgr.copyItem(atPath: filePath, toPath: destPath) + NSWorkspace.shared().selectFile(destPath, inFileViewerRootedAtPath: dataPath) } } } diff --git a/ShadowsocksX-NG/StatusItemView.swift b/ShadowsocksX-NG/StatusItemView.swift index 07d9a20..0441207 100755 --- a/ShadowsocksX-NG/StatusItemView.swift +++ b/ShadowsocksX-NG/StatusItemView.swift @@ -9,14 +9,14 @@ import AppKit import Foundation -public class StatusItemView: NSControl { +open class StatusItemView: NSControl { static let KB:Float = 1024 static let MB:Float = KB*1024 static let GB:Float = MB*1024 static let TB:Float = GB*1024 var fontSize:CGFloat = 9 - var fontColor = NSColor.blackColor() + var fontColor = NSColor.black var darkMode = false var mouseDown = false var statusItem:NSStatusItem @@ -42,30 +42,30 @@ public class StatusItemView: NSControl { fatalError("init(coder:) has not been implemented") } - public override func drawRect(dirtyRect: NSRect) { - statusItem.drawStatusBarBackgroundInRect(dirtyRect, withHighlight: mouseDown) + open override func draw(_ dirtyRect: NSRect) { + statusItem.drawStatusBarBackground(in: dirtyRect, withHighlight: mouseDown) - fontColor = (darkMode||mouseDown) ? NSColor.whiteColor() : NSColor.blackColor() - let fontAttributes = [NSFontAttributeName: NSFont.systemFontOfSize(fontSize), NSForegroundColorAttributeName: fontColor] + fontColor = (darkMode||mouseDown) ? NSColor.white : NSColor.black + let fontAttributes = [NSFontAttributeName: NSFont.systemFont(ofSize: fontSize), NSForegroundColorAttributeName: fontColor] as [String : Any] if showSpeed{ let upRateString = NSAttributedString(string: upRate+" ↑", attributes: fontAttributes) - let upRateRect = upRateString.boundingRectWithSize(NSSize(width: 100, height: 100), options: .UsesLineFragmentOrigin) - upRateString.drawAtPoint(NSMakePoint(bounds.width - upRateRect.width - 5, 10)) + let upRateRect = upRateString.boundingRect(with: NSSize(width: 100, height: 100), options: .usesLineFragmentOrigin) + upRateString.draw(at: NSMakePoint(bounds.width - upRateRect.width - 5, 10)) let downRateString = NSAttributedString(string: downRate+" ↓", attributes: fontAttributes) - let downRateRect = downRateString.boundingRectWithSize(NSSize(width: 100, height: 100), options: .UsesLineFragmentOrigin) - downRateString.drawAtPoint(NSMakePoint(bounds.width - downRateRect.width - 5, 0)) + let downRateRect = downRateString.boundingRect(with: NSSize(width: 100, height: 100), options: .usesLineFragmentOrigin) + downRateString.draw(at: NSMakePoint(bounds.width - downRateRect.width - 5, 0)) } - image?.drawAtPoint(NSPoint(x: 0, y: 0), fromRect: NSRect(x: 0, y: 0, width: bounds.height, height: bounds.height), operation: NSCompositeSourceOver, fraction: 1.0) + image?.draw(at: NSPoint(x: 0, y: 0), from: NSRect(x: 0, y: 0, width: bounds.height, height: bounds.height), operation: NSCompositeSourceOver, fraction: 1.0) } - public func setRateData(up up:Float, down: Float) { + open func setRateData(up:Float, down: Float) { upRate = formatRateData(up) downRate = formatRateData(down) setNeedsDisplay() } - func formatRateData(data:Float) -> String { + func formatRateData(_ data:Float) -> String { var result:Float var unit: String @@ -110,7 +110,7 @@ public class StatusItemView: NSControl { setNeedsDisplay() } - func setIcon(image: NSImage) { + func setIcon(_ image: NSImage) { self.image = image setNeedsDisplay() } @@ -119,16 +119,16 @@ public class StatusItemView: NSControl { //action extension StatusItemView: NSMenuDelegate{ - public override func mouseDown(theEvent: NSEvent) { - statusItem.popUpStatusItemMenu(menu!) + open override func mouseDown(with theEvent: NSEvent) { + statusItem.popUpMenu(menu!) } - public func menuWillOpen(menu: NSMenu) { + public func menuWillOpen(_ menu: NSMenu) { mouseDown = true setNeedsDisplay() } - public func menuDidClose(menu: NSMenu) { + public func menuDidClose(_ menu: NSMenu) { mouseDown = false setNeedsDisplay() } diff --git a/ShadowsocksX-NG/SystemThemeChangeHelper.swift b/ShadowsocksX-NG/SystemThemeChangeHelper.swift index 57fdea9..ac4b734 100644 --- a/ShadowsocksX-NG/SystemThemeChangeHelper.swift +++ b/ShadowsocksX-NG/SystemThemeChangeHelper.swift @@ -8,17 +8,17 @@ import Foundation -public class SystemThemeChangeHelper { +open class SystemThemeChangeHelper { static func addRespond(target aTarget: AnyObject, selector aSelector: Selector) { - NSDistributedNotificationCenter.defaultCenter().addObserver(aTarget, selector: aSelector, name: "AppleInterfaceThemeChangedNotification", object: nil) + DistributedNotificationCenter.default().addObserver(aTarget, selector: aSelector, name: NSNotification.Name(rawValue: "AppleInterfaceThemeChangedNotification"), object: nil) } static func isCurrentDark() -> Bool { var result = false - let dict = NSUserDefaults.standardUserDefaults().persistentDomainForName(NSGlobalDomain) - if let style:AnyObject = dict!["AppleInterfaceStyle"] { - if (style as! String).caseInsensitiveCompare("dark") == NSComparisonResult.OrderedSame { + let dict = UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain) + if let style:AnyObject = dict!["AppleInterfaceStyle"] as AnyObject? { + if (style as! String).caseInsensitiveCompare("dark") == ComparisonResult.orderedSame { result = true } } diff --git a/ShadowsocksX-NG/UserRulesController.swift b/ShadowsocksX-NG/UserRulesController.swift index 3e020cc..f378ca3 100644 --- a/ShadowsocksX-NG/UserRulesController.swift +++ b/ShadowsocksX-NG/UserRulesController.swift @@ -15,36 +15,36 @@ class UserRulesController: NSWindowController { override func windowDidLoad() { super.windowDidLoad() - let fileMgr = NSFileManager.defaultManager() - if !fileMgr.fileExistsAtPath(PACUserRuleFilePath) { - let src = NSBundle.mainBundle().pathForResource("user-rule", ofType: "txt") - try! fileMgr.copyItemAtPath(src!, toPath: PACUserRuleFilePath) + let fileMgr = FileManager.default + if !fileMgr.fileExists(atPath: PACUserRuleFilePath) { + let src = Bundle.main.path(forResource: "user-rule", ofType: "txt") + try! fileMgr.copyItem(atPath: src!, toPath: PACUserRuleFilePath) } - let str = try? String(contentsOfFile: PACUserRuleFilePath, encoding: NSUTF8StringEncoding) + let str = try? String(contentsOfFile: PACUserRuleFilePath, encoding: String.Encoding.utf8) userRulesView.string = str } - @IBAction func didCancel(sender: AnyObject) { + @IBAction func didCancel(_ sender: AnyObject) { window?.performClose(self) } - @IBAction func didOK(sender: AnyObject) { + @IBAction func didOK(_ sender: AnyObject) { if let str = userRulesView.string { do { - try str.dataUsingEncoding(NSUTF8StringEncoding)?.writeToFile(PACUserRuleFilePath, options: .DataWritingAtomic) + 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.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) } else { let notification = NSUserNotification() notification.title = "It's failed to update PAC by User Rules.".localized - NSUserNotificationCenter.defaultUserNotificationCenter() - .deliverNotification(notification) + NSUserNotificationCenter.default + .deliver(notification) } } catch {} } diff --git a/ShadowsocksX-NG/Utils.swift b/ShadowsocksX-NG/Utils.swift index d14670b..74c0f54 100644 --- a/ShadowsocksX-NG/Utils.swift +++ b/ShadowsocksX-NG/Utils.swift @@ -11,17 +11,17 @@ import Foundation extension String { var localized: String { - return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "") + return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "") } } -extension NSData { +extension Data { func sha1() -> String { let data = self - var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0) - CC_SHA1(data.bytes, CC_LONG(data.length), &digest) + var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH)) + CC_SHA1((data as NSData).bytes, CC_LONG(data.count), &digest) let hexBytes = digest.map { String(format: "%02hhx", $0) } - return hexBytes.joinWithSeparator("") + return hexBytes.joined(separator: "") } -} \ No newline at end of file +} diff --git a/ShadowsocksX-NGTests/ShadowsocksX_NGTests.swift b/ShadowsocksX-NGTests/ShadowsocksX_NGTests.swift index a7da392..4bab66f 100644 --- a/ShadowsocksX-NGTests/ShadowsocksX_NGTests.swift +++ b/ShadowsocksX-NGTests/ShadowsocksX_NGTests.swift @@ -28,7 +28,7 @@ class ShadowsocksX_NGTests: XCTestCase { func testPerformanceExample() { // This is an example of a performance test case. - self.measureBlock { + self.measure { // Put the code you want to measure the time of here. } }