source: launchers/macosx/I2PLauncher/SwiftMainDelegate.swift @ a367778

Last change on this file since a367778 was a367778, checked in by meeh <meeh@…>, 2 years ago

Mac OSX Launcher: Misc changes + xcode project file update

  • Property mode set to 100644
File size: 5.3 KB
Line 
1//
2//  SwiftMainDelegate.swift
3//  I2PLauncher
4//
5//  Created by Mikal Villa on 17/09/2018.
6//  Copyright © 2018 The I2P Project. All rights reserved.
7//
8
9import Foundation
10import Cocoa
11
12extension Notification.Name {
13  static let killLauncher = Notification.Name("killStartupLauncher")
14}
15
16class Logger {
17  static func MLog<T>(level:Int32, _ object: T?,file:String = #file, function:String = #function, line:Int = #line) {
18    SBridge.logProxy(level, formattedMsg: "\(makeTag(function: function, file: file, line: line)) : \(object)")
19  }
20 
21  private static func makeTag(function: String, file: String, line: Int) -> String{
22    let url = NSURL(fileURLWithPath: file)
23    let className:String! = url.lastPathComponent == nil ? file: url.lastPathComponent!
24    return "\(className) \(function)[\(line)]"
25  }
26 
27}
28
29
30@objc class SwiftMainDelegate : NSObject {
31 
32  let statusBarController = StatusBarController()
33  let sharedRouterMgmr = RouterManager.shared()
34 
35  override init() {
36    super.init()
37    if (!DetectJava.shared().isJavaFound()) {
38    DetectJava.shared().findIt()
39      if (!DetectJava.shared().isJavaFound()) {
40        Logger.MLog(level:3, "Could not find java....")
41        terminate("No java..")
42      }
43    }
44    let javaBinPath = DetectJava.shared().javaBinary
45    Logger.MLog(level:1, "".appendingFormat("Found java home = %@", javaBinPath!))
46   
47    let (portIsNotTaken, _) = RouterProcessStatus.checkTcpPortForListen(port: 7657)
48    if (!portIsNotTaken) {
49      RouterProcessStatus.isRouterRunning = true
50      RouterProcessStatus.isRouterChildProcess = false
51      Logger.MLog(level:2, "I2P Router seems to be running")
52    } else {
53      RouterProcessStatus.isRouterRunning = false
54      Logger.MLog(level:2, "I2P Router seems to NOT be running")
55    }
56  } // End of init()
57 
58  @objc func findInstalledI2PVersion() {
59    var i2pPath = Preferences.shared().i2pBaseDirectory
60    let jExecPath:String = Preferences.shared().javaCommandPath
61   
62    let jarPath = i2pPath + "/lib/i2p.jar"
63   
64    let subCmd = jExecPath + "-cp " + jarPath + " net.i2p.CoreVersion"
65   
66    let cmdArgs:[String] = ["-c", subCmd]
67    print(cmdArgs)
68    let sub:Subprocess = Subprocess.init(executablePath: "/bin/sh", arguments: cmdArgs)
69    let results:ExecutionResult = sub.execute(captureOutput: true)!
70    if (results.didCaptureOutput) {
71      if (results.status == 0) {
72        let i2pVersion = results.outputLines.first?.replace(target: "I2P Core version: ", withString: "")
73        Logger.MLog(level: 1, "".appendingFormat("I2P version detected: %@",i2pVersion ?? "Unknown"))
74        RouterProcessStatus.routerVersion = i2pVersion
75        RouterManager.shared().eventManager.trigger(eventName: "router_version", information: i2pVersion)
76      } else {
77        Logger.MLog(level: 2, "Non zero exit code from subprocess while trying to detect version number!")
78        for line in results.errorsLines {
79          Logger.MLog(level: 2, line)
80        }
81      }
82    } else {
83      Logger.MLog(level: 1, "Warning: Version Detection did NOT captured output")
84    }
85  }
86 
87  func triggerDockIconShowHide(showIcon state: Bool) -> Bool {
88    var result: Bool
89    if state {
90      result = NSApp.setActivationPolicy(NSApplicationActivationPolicy.regular)
91    } else {
92      result = NSApp.setActivationPolicy(NSApplicationActivationPolicy.accessory)
93    }
94    return result
95  }
96 
97  func getDockIconStateIsShowing() -> Bool {
98    if NSApp.activationPolicy() == NSApplicationActivationPolicy.regular {
99      return true
100    } else {
101      return false
102    }
103  }
104 
105  @objc func applicationDidFinishLaunching() {
106    switch Preferences.shared().showAsIconMode {
107    case .bothIcon, .dockIcon:
108      if (!getDockIconStateIsShowing()) {
109        triggerDockIconShowHide(showIcon: true)
110      }
111    default:
112      if (getDockIconStateIsShowing()) {
113        triggerDockIconShowHide(showIcon: false)
114      }
115    }
116    let launcherAppId = "net.i2p.bootstrap.macosx.StartupItemApp"
117    let runningApps = NSWorkspace.shared().runningApplications
118    let isRunning = !runningApps.filter { $0.bundleIdentifier == launcherAppId }.isEmpty
119    // SMLoginItemSetEnabled(launcherAppId as CFString, true)
120   
121    if isRunning {
122      DistributedNotificationCenter.default().post(name: .killLauncher, object: Bundle.main.bundleIdentifier!)
123    }
124  }
125 
126  @objc func listenForEvent(eventName: String, callbackActionFn: @escaping ((Any?)->()) ) {
127    RouterManager.shared().eventManager.listenTo(eventName: eventName, action: callbackActionFn )
128  }
129 
130  @objc func triggerEvent(en: String, details: String? = nil) {
131    RouterManager.shared().eventManager.trigger(eventName: en, information: details)
132  }
133 
134  @objc static func openLink(url: String) {
135    NSLog("Trying to open \(url)")
136    NSWorkspace.shared().open(NSURL(string: url)! as URL)
137  }
138 
139  @objc func applicationWillTerminate() {
140    // Shutdown stuff
141    if (Preferences.shared().stopRouterOnLauncherShutdown) {
142      RouterManager.shared().routerRunner.TeardownLaunchd()
143      sleep(2)
144      let status: AgentStatus? = RouterRunner.launchAgent?.status()
145      if status != .unloaded {
146        Logger.MLog(level:2, "Router service not yet stopped")
147        RouterManager.shared().routerRunner.TeardownLaunchd()
148        sleep(5)
149      }
150    }
151  }
152 
153  @objc func terminate(_ why: Any?) {
154    Logger.MLog(level:2, "".appendingFormat("Stopping cause of ", why! as! CVarArg))
155  }
156}
157
Note: See TracBrowser for help on using the repository browser.