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

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

Mac OS X Launcher: Adding optional Dock Icon functionality

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