source: launchers/macosx/main.mm @ e45963d

Last change on this file since e45963d was e45963d, checked in by meeh <meeh@…>, 14 months ago

Mac OSX Launcher: main.mm updated to use the new swift main class name.

  • Property mode set to 100644
File size: 7.7 KB
Line 
1#include <functional>
2#include <memory>
3#include <iostream>
4#include <algorithm>
5#include <string>
6#include <list>
7#include <sys/stat.h>
8#include <stdlib.h>
9#include <future>
10#include <vector>
11
12#import <Foundation/Foundation.h>
13#import <Foundation/NSFileManager.h>
14#include <CoreFoundation/CFPreferences.h>
15
16#import <objc/Object.h>
17#import <Cocoa/Cocoa.h>
18#import <AppKit/AppKit.h>
19#import <AppKit/NSApplication.h>
20
21#import "I2PLauncher-Swift.h"
22
23#include "AppDelegate.h"
24#include "RouterTask.h"
25#include "include/fn.h"
26#include "include/portcheck.h"
27#import "SBridge.h"
28#import "Deployer.h"
29#include "logger_c.h"
30
31#ifdef __cplusplus
32#include <string>
33
34#include "include/subprocess.hpp"
35#include "include/strutil.hpp"
36
37#include "Logger.h"
38#include "LoggerWorker.hpp"
39
40using namespace subprocess;
41#endif
42
43#define debug(format, ...) CFShow([NSString stringWithFormat:format, ## __VA_ARGS__]);
44
45
46
47@interface AppDelegate () <NSUserNotificationCenterDelegate, NSApplicationDelegate>
48@end
49
50
51@implementation ExtractMetaInfo : NSObject
52@end
53
54
55@implementation AppDelegate
56
57- (void) awakeFromNib {
58}
59
60
61- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center
62     shouldPresentNotification:(NSUserNotification *)notification {
63  return YES;
64}
65
66- (void)extractI2PBaseDir:(void(^)(BOOL success, NSError *error))completion
67{
68  self.deployer = [[I2PDeployer alloc] initWithMetaInfo:self.metaInfo];
69  [self.deployer extractI2PBaseDir:completion];
70}
71
72- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
73  // Init application here
74 
75  // Here we initialize the swift code which would do most of the job from now on.
76  self.swiftRuntime = [[SwiftApplicationDelegate alloc] init];
77 
78  // This setup allows the application to send notifications
79  [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
80 
81 
82  // Start with user preferences
83  self.userPreferences = [NSUserDefaults standardUserDefaults];
84  // In case we are unbundled, make us a proper UI application
85  [NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];
86  [NSApp activateIgnoringOtherApps:YES];
87
88
89#ifdef __cplusplus
90
91  RouterProcessStatus* routerStatus = [[RouterProcessStatus alloc] init];
92  std::string i2pBaseDir(getDefaultBaseDir());
93  MLOG(INFO) << "i2pBaseDir = " << i2pBaseDir.c_str();
94  bool shouldAutoStartRouter = false;
95 
96  // Initialize the Swift environment (the UI components)
97  [self.swiftRuntime applicationDidFinishLaunching];
98 
99  NSInteger portNum = [self.userPreferences integerForKey:@"consolePortCheckNum"];
100  if (port_check((int)portNum) != 0)
101  {
102    NSLog(@"Seems i2p is already running - I will not start the router (port %d is in use..)", (int)portNum);
103    sendUserNotification(@"Found already running router", @"TCP port 7657 seem to be used by another i2p instance.");
104   
105    [routerStatus setRouterStatus: true];
106    [routerStatus setRouterRanByUs: false];
107    shouldAutoStartRouter = false;
108  } else {
109    shouldAutoStartRouter = true;
110  }
111  if (![self.userPreferences boolForKey:@"startRouterAtLogin"] && ![self.userPreferences boolForKey:@"startRouterAtStartup"])
112  {
113    // In this case we don't want to find a running service
114    std::string launchdFile(RealHomeDirectory());
115    launchdFile += "/Library/LaunchAgents/net.i2p.macosx.I2PRouter.plist";
116   
117  }
118
119  NSBundle *launcherBundle = [NSBundle mainBundle];
120 
121 
122  // Helper object to hold statefull path information
123  self.metaInfo = [[ExtractMetaInfo alloc] init];
124  self.metaInfo.i2pBase = [NSString stringWithUTF8String:i2pBaseDir.c_str()];
125  self.metaInfo.javaBinary = [routerStatus getJavaHome];
126  self.metaInfo.jarFile = [launcherBundle pathForResource:@"launcher" ofType:@"jar"];
127  self.metaInfo.zipFile = [launcherBundle pathForResource:@"base" ofType:@"zip"];
128
129  std::string basearg("-Di2p.dir.base=");
130  basearg += i2pBaseDir;
131
132  std::string jarfile("-cp ");
133  jarfile += [self.metaInfo.zipFile UTF8String];
134 
135  // This will trigger the router start after an upgrade.
136  [routerStatus listenForEventWithEventName:@"router_must_upgrade" callbackActionFn:^(NSString* information) {
137    NSLog(@"Got signal, router must be deployed from base.zip");
138    [self extractI2PBaseDir:^(BOOL success, NSError *error) {
139      if (success) {
140        sendUserNotification(@"I2P is done extracting", @"I2P is now installed and ready to run!");
141        NSLog(@"Done extracting I2P");
142        [routerStatus triggerEventWithEn:@"extract_completed" details:@"upgrade complete"];
143      } else {
144        NSLog(@"Error while extracting I2P");
145        [routerStatus triggerEventWithEn:@"extract_errored" details:[NSString stringWithFormat:@"%@", error]];
146      }
147    }];
148  }];
149 
150  NSString *nsI2PBaseStr = [NSString stringWithUTF8String:i2pBaseDir.c_str()];
151
152  [routerStatus listenForEventWithEventName:@"extract_completed" callbackActionFn:^(NSString* information) {
153    NSLog(@"Time to detect I2P version in install directory");
154    [self.swiftRuntime findInstalledI2PVersion];
155  }];
156 
157  //struct stat sb;
158  //if ( !(stat(i2pBaseDir.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) )
159  BOOL shouldBeTrueOnReturnDir = YES;
160  if (! [NSFileManager.defaultManager fileExistsAtPath: nsI2PBaseStr isDirectory: &shouldBeTrueOnReturnDir])
161  {
162    // I2P is not extracted.
163    if (shouldBeTrueOnReturnDir) {
164      if (self.enableVerboseLogging) NSLog(@"I2P Directory don't exists!");
165      [routerStatus triggerEventWithEn:@"router_must_upgrade" details:@"deploy needed"];
166    } else {
167      // TODO: handle if i2p path exists but it's not a dir.
168    }
169  } else {
170    // I2P was already found extracted
171    NSString *nsI2pJar = [NSString stringWithFormat:@"%@/lib/i2p.jar", nsI2PBaseStr];
172   
173    // But does I2PBASE/lib/i2p.jar exists?
174    if ([NSFileManager.defaultManager fileExistsAtPath:nsI2pJar]) {
175      NSLog(@"Time to detect I2P version in install directory");
176      [self.swiftRuntime findInstalledI2PVersion];
177    } else {
178      // The directory exists, but not i2p.jar - most likely we're in mid-extraction state.
179      [routerStatus triggerEventWithEn:@"router_must_upgrade" details:@"deploy needed"];
180    }
181  }
182 
183#endif
184}
185
186/**
187 *
188 * Exit sequence
189 *
190 **/
191- (void)applicationWillTerminate:(NSNotification *)aNotification {
192  // Tear down here
193  [self.swiftRuntime applicationWillTerminate];
194  NSString *string = @"applicationWillTerminate executed";
195  NSLog(@"%@", string);
196  [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:nil];
197}
198
199
200/* wrapper for main */
201- (AppDelegate *)initWithArgc:(int)argc argv:(const char **)argv {
202  return self;
203}
204@end
205
206#ifdef __cplusplus
207namespace {
208  const std::string logDirectory = getDefaultLogDir();
209}
210#endif
211
212int main(int argc, const char **argv)
213{
214  NSApplication *app = [NSApplication sharedApplication];
215
216#ifdef __cplusplus
217  mkdir(logDirectory.c_str(), S_IRUSR | S_IWUSR | S_IXUSR);
218 
219  SharedLogWorker logger("I2PLauncher", logDirectory);
220  MeehLog::initializeLogging(&logger);
221 
222  MLOG(INFO) << "Application is starting up";
223#endif
224 
225  AppDelegate *appDelegate = [[AppDelegate alloc] initWithArgc:argc argv:argv];
226  app.delegate = appDelegate;
227  auto mainBundle = [NSBundle mainBundle];
228  NSString* stringNameBundle = [mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey];
229  if ([[NSRunningApplication runningApplicationsWithBundleIdentifier:[mainBundle bundleIdentifier]] count] > 1) {
230    [[NSAlert alertWithMessageText:[NSString stringWithFormat:@"Another copy of %@ is already running.",stringNameBundle]
231                     defaultButton:nil alternateButton:nil otherButton:nil informativeTextWithFormat:@"This copy will now quit."] runModal];
232   
233    [NSApp terminate:nil];
234  }
235#pragma GCC diagnostic push
236#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
237  [NSBundle loadNibNamed:@"I2Launcher" owner:NSApp];
238#pragma GCC diagnostic pop
239 
240  [NSApp run];
241  return 0;
242}
243
244
245
Note: See TracBrowser for help on using the repository browser.