Mac OSX Launcher: Cleaned, updated and renamed main swift class.

This commit is contained in:
meeh
2019-05-02 22:50:12 +00:00
parent 3e10745717
commit 66deb5dc7e
2 changed files with 92 additions and 119 deletions

View File

@@ -1,91 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1000"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BF5061672113C48E0014EB07"
BuildableName = "I2PLauncher.app"
BlueprintName = "I2PLauncher"
ReferencedContainer = "container:I2PLauncher.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BF5061672113C48E0014EB07"
BuildableName = "I2PLauncher.app"
BlueprintName = "I2PLauncher"
ReferencedContainer = "container:I2PLauncher.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BF5061672113C48E0014EB07"
BuildableName = "I2PLauncher.app"
BlueprintName = "I2PLauncher"
ReferencedContainer = "container:I2PLauncher.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "BF5061672113C48E0014EB07"
BuildableName = "I2PLauncher.app"
BlueprintName = "I2PLauncher"
ReferencedContainer = "container:I2PLauncher.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@@ -8,32 +8,41 @@
import Foundation
import Cocoa
import MBPopup
extension Notification.Name {
static let killLauncher = Notification.Name("killStartupLauncher")
static let upgradeRouter = Notification.Name("upgradeRouter")
static let startRouter = Notification.Name("startRouter")
static let stopRouter = Notification.Name("stopRouter")
}
class Logger {
static func MLog<T>(level:Int32, _ object: T?,file:String = #file, function:String = #function, line:Int = #line) {
SBridge.logProxy(level, formattedMsg: "\(makeTag(function: function, file: file, line: line)) : \(object)")
SBridge.logProxy(level, formattedMsg: "\(makeTag(function: function, file: file, line: line)) : \(String(describing: object))")
}
private static func makeTag(function: String, file: String, line: Int) -> String{
let url = NSURL(fileURLWithPath: file)
let className:String! = url.lastPathComponent == nil ? file: url.lastPathComponent!
return "\(className) \(function)[\(line)]"
return "\(String(describing: className)) \(function)[\(line)]"
}
}
@objc class SwiftMainDelegate : NSObject {
@objc class SwiftApplicationDelegate : NSObject, NSApplicationDelegate, NSMenuDelegate {
let statusBarController = StatusBarController()
let sharedRouterMgmr = RouterManager.shared()
//let popupController: MBPopupController
//let serviceTableViewController = ServiceTableViewController()
//let editorTableViewController: EditorTableViewController
// Constructor, think of it like an early entrypoint.
override init() {
//self.popupController = MBPopupController(contentView: serviceTableViewController.contentView)
//self.editorTableViewController = serviceTableViewController.editorTableViewController
super.init()
if (!DetectJava.shared().isJavaFound()) {
@@ -46,7 +55,7 @@ class Logger {
let javaBinPath = DetectJava.shared().javaBinary
Logger.MLog(level:1, "".appendingFormat("Found java home = %@", javaBinPath!))
let (portIsNotTaken, _) = RouterProcessStatus.checkTcpPortForListen(port: 7657)
let (portIsNotTaken, _) = NetworkUtil.checkTcpPortForListen(port: 7657)
if (!portIsNotTaken) {
RouterProcessStatus.isRouterRunning = true
RouterProcessStatus.isRouterChildProcess = false
@@ -58,33 +67,33 @@ class Logger {
} // End of init()
// A function which detects the current installed I2P router version
@objc func findInstalledI2PVersion() {
var i2pPath = Preferences.shared().i2pBaseDirectory
let jExecPath:String = Preferences.shared().javaCommandPath
let jarPath = i2pPath + "/lib/i2p.jar"
let subCmd = jExecPath + "-cp " + jarPath + " net.i2p.CoreVersion"
// NOTE: The return value tells if the function fails to detect I2P or not, and not if I2P is installed or not.
@objc func findInstalledI2PVersion() -> Bool {
let jarPath = Preferences.shared().i2pBaseDirectory + "/lib/i2p.jar"
let subCmd = Preferences.shared().javaCommandPath + "-cp " + jarPath + " net.i2p.CoreVersion"
let cmdArgs:[String] = ["-c", subCmd]
print(cmdArgs)
let sub:Subprocess = Subprocess.init(executablePath: "/bin/sh", arguments: cmdArgs)
let results:ExecutionResult = sub.execute(captureOutput: true)!
if (results.didCaptureOutput) {
if (results.status == 0) {
let i2pVersion = results.outputLines.first?.replace(target: "I2P Core version: ", withString: "")
Logger.MLog(level: 1, "".appendingFormat("I2P version detected: %@",i2pVersion ?? "Unknown"))
RouterProcessStatus.routerVersion = i2pVersion
RouterManager.shared().eventManager.trigger(eventName: "router_version", information: i2pVersion)
return true
} else {
Logger.MLog(level: 2, "Non zero exit code from subprocess while trying to detect version number!")
for line in results.errorsLines {
Logger.MLog(level: 2, line)
}
return false
}
} else {
Logger.MLog(level: 1, "Warning: Version Detection did NOT captured output")
}
return false
}
@@ -92,22 +101,35 @@ class Logger {
func triggerDockIconShowHide(showIcon state: Bool) -> Bool {
var result: Bool
if state {
result = NSApp.setActivationPolicy(NSApplicationActivationPolicy.regular)
result = NSApp.setActivationPolicy(NSApplication.ActivationPolicy.regular)
} else {
result = NSApp.setActivationPolicy(NSApplicationActivationPolicy.accessory)
result = NSApp.setActivationPolicy(NSApplication.ActivationPolicy.accessory)
}
return result
}
// Helper functions for the optional dock icon
func getDockIconStateIsShowing() -> Bool {
if NSApp.activationPolicy() == NSApplicationActivationPolicy.regular {
if NSApp.activationPolicy() == NSApplication.ActivationPolicy.regular {
return true
} else {
return false
}
}
@objc func updateServices() {
/*
serviceTableViewController.updateServices { [weak self] in
let title = self?.serviceTableViewController.generalStatus == .crashed ? "-.-" : "I2PLauncher"
self?.popupController.statusItem.title = title
if Preferences.shared().notifyOnStatusChange {
self?.serviceTableViewController.services.forEach { $0.notifyIfNecessary() }
}
}
*/
}
/**
*
* This is the swift "entrypoint". In C it would been "main(argc,argv)"
@@ -117,30 +139,60 @@ class Logger {
switch Preferences.shared().showAsIconMode {
case .bothIcon, .dockIcon:
if (!getDockIconStateIsShowing()) {
triggerDockIconShowHide(showIcon: true)
let _ = triggerDockIconShowHide(showIcon: true)
}
default:
if (getDockIconStateIsShowing()) {
triggerDockIconShowHide(showIcon: false)
let _ = triggerDockIconShowHide(showIcon: false)
}
}
let launcherAppId = "net.i2p.bootstrap.macosx.StartupItemApp"
let runningApps = NSWorkspace.shared().runningApplications
let isRunning = !runningApps.filter { $0.bundleIdentifier == launcherAppId }.isEmpty
let runningApps = NSWorkspace.shared.runningApplications
let isRunning = !runningApps.filter { $0.bundleIdentifier == Identifiers.launcherApplicationBundleId }.isEmpty
// SMLoginItemSetEnabled(launcherAppId as CFString, true)
if isRunning {
DistributedNotificationCenter.default().post(name: .killLauncher, object: Bundle.main.bundleIdentifier!)
}
if (Preferences.shared().alsoStartFirefoxOnLaunch)
{
// TODO: For some reason it does not seem to obay the two minutes delay.
// If set, execute i2p browser / firefox after two minutes.
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
FirefoxManager.shared().executeFirefox()
if (Preferences.shared().alsoStartFirefoxOnLaunch) {
DispatchQueue.delay(.seconds(120)) {
print("two minutes has passed, executing firefox manager")
let _ = FirefoxManager.shared().executeFirefox()
}
}
if #available(OSX 10.14, *) {
Appearance.addObserver(self)
} else {
//popupController.backgroundView.backgroundColor = .white
}
NSUserNotificationCenter.default.delegate = self
/*
popupController.statusItem.button?.image = NSImage(named:"StatusBarButtonImage")
popupController.statusItem.button?.toolTip = "I2P Launch Manager"
popupController.statusItem.button?.font = NSFont(name: "SF Mono Regular", size: 10) ?? NSFont.systemFont(ofSize: 12)
popupController.statusItem.length = 30
popupController.contentView.wantsLayer = true
popupController.contentView.layer?.masksToBounds = true
serviceTableViewController.setup()
popupController.willOpenPopup = { [weak self] _ in
if self?.editorTableViewController.hidden == true {
self?.serviceTableViewController.willOpenPopup()
} else {
self?.editorTableViewController.willOpenPopup()
}
}
popupController.didOpenPopup = { [weak self] in
if self?.editorTableViewController.hidden == false {
self?.editorTableViewController.didOpenPopup()
}
}
*/
}
@objc func listenForEvent(eventName: String, callbackActionFn: @escaping ((Any?)->()) ) {
@@ -153,7 +205,7 @@ class Logger {
@objc static func openLink(url: String) {
NSLog("Trying to open \(url)")
NSWorkspace.shared().open(NSURL(string: url)! as URL)
NSWorkspace.shared.open(NSURL(string: url)! as URL)
}
/**
@@ -181,3 +233,15 @@ class Logger {
}
}
extension SwiftApplicationDelegate: NSUserNotificationCenterDelegate {
func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) {
//popupController.openPopup()
}
}
extension SwiftApplicationDelegate: AppearanceObserver {
func changeAppearance(to newAppearance: NSAppearance) {
//popupController.backgroundView.backgroundColor = newAppearance.isDarkMode ? .windowBackgroundColor : .white
}
}