source: launchers/macosx/main.mm @ ba853a8c

Last change on this file since ba853a8c was dfcc616, checked in by meeh <meeh@…>, 21 months ago

Mac OS X Launcher: Misc changes in ObjC, forwarding sendUserNotification to Swift.

  • Property mode set to 100644
File size: 8.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)setApplicationDefaultPreferences {
73  [self.userPreferences registerDefaults:@{
74    @"enableLogging": @YES,
75    @"enableVerboseLogging": @YES,
76    @"autoStartRouterAtBoot": @NO,
77    @"startLauncherAtLogin": @NO,
78    @"startRouterAtStartup": @YES,
79    @"stopRouterAtShutdown": @YES,
80    @"letRouterLiveEvenLauncherDied": @NO,
81    @"consolePortCheckNum": @7657,
82    @"i2pBaseDirectory": (NSString *)CFStringCreateWithCString(NULL, const_cast<const char *>(getDefaultBaseDir().c_str()), kCFStringEncodingUTF8)
83  }];
84
85  auto dict = [self.userPreferences dictionaryRepresentation];
86  [self.userPreferences setPersistentDomain:dict forName:NSAPPDOMAIN];
87
88  CFPreferencesSetMultiple((CFDictionaryRef)dict, NULL, CFAPPDOMAIN, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
89  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
90
91  NSLog(@"Default preferences stored!");
92}
93
94
95- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
96  // Init application here
97 
98  self.swiftRuntime = [[SwiftMainDelegate alloc] init];
99 
100  // This setup allows the application to send notifications
101  [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
102 
103 
104  // Start with user preferences
105  self.userPreferences = [NSUserDefaults standardUserDefaults];
106  [self setApplicationDefaultPreferences];
107  self.enableLogging = [self.userPreferences boolForKey:@"enableLogging"];
108  self.enableVerboseLogging = [self.userPreferences boolForKey:@"enableVerboseLogging"];
109  // In case we are unbundled, make us a proper UI application
110  [NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];
111  [NSApp activateIgnoringOtherApps:YES];
112
113
114#ifdef __cplusplus
115
116  RouterProcessStatus* routerStatus = [[RouterProcessStatus alloc] init];
117  std::string i2pBaseDir(getDefaultBaseDir());
118  MLOG(INFO) << "i2pBaseDir = " << i2pBaseDir.c_str();
119  bool shouldAutoStartRouter = false;
120 
121  // Initialize the Swift environment (the UI components)
122  [self.swiftRuntime applicationDidFinishLaunching];
123 
124  NSInteger portNum = [self.userPreferences integerForKey:@"consolePortCheckNum"];
125  if (port_check((int)portNum) != 0)
126  {
127    NSLog(@"Seems i2p is already running - I will not start the router (port %d is in use..)", (int)portNum);
128    sendUserNotification(@"Found already running router", @"TCP port 7657 seem to be used by another i2p instance.");
129   
130    [routerStatus setRouterStatus: true];
131    [routerStatus setRouterRanByUs: false];
132    shouldAutoStartRouter = false;
133  } else {
134    shouldAutoStartRouter = true;
135  }
136  if (![self.userPreferences boolForKey:@"startRouterAtLogin"] && ![self.userPreferences boolForKey:@"startRouterAtStartup"])
137  {
138    // In this case we don't want to find a running service
139    std::string launchdFile(RealHomeDirectory());
140    launchdFile += "/Library/LaunchAgents/net.i2p.macosx.I2PRouter.plist";
141   
142  }
143
144  NSBundle *launcherBundle = [NSBundle mainBundle];
145 
146 
147  // Helper object to hold statefull path information
148  self.metaInfo = [[ExtractMetaInfo alloc] init];
149  self.metaInfo.i2pBase = [NSString stringWithUTF8String:i2pBaseDir.c_str()];
150  self.metaInfo.javaBinary = [routerStatus getJavaHome];
151  self.metaInfo.jarFile = [launcherBundle pathForResource:@"launcher" ofType:@"jar"];
152  self.metaInfo.zipFile = [launcherBundle pathForResource:@"base" ofType:@"zip"];
153
154  std::string basearg("-Di2p.dir.base=");
155  basearg += i2pBaseDir;
156
157  std::string jarfile("-cp ");
158  jarfile += [self.metaInfo.zipFile UTF8String];
159 
160  // This will trigger the router start after an upgrade.
161  [routerStatus listenForEventWithEventName:@"router_must_upgrade" callbackActionFn:^(NSString* information) {
162    NSLog(@"Got signal, router must be deployed from base.zip");
163    [self extractI2PBaseDir:^(BOOL success, NSError *error) {
164      if (success) {
165        sendUserNotification(@"I2P is done extracting", @"I2P is now installed and ready to run!");
166        NSLog(@"Done extracting I2P");
167        [routerStatus triggerEventWithEn:@"extract_completed" details:@"upgrade complete"];
168      } else {
169        NSLog(@"Error while extracting I2P");
170        [routerStatus triggerEventWithEn:@"extract_errored" details:[NSString stringWithFormat:@"%@", error]];
171      }
172    }];
173  }];
174 
175  NSString *nsI2PBaseStr = [NSString stringWithUTF8String:i2pBaseDir.c_str()];
176
177  [routerStatus listenForEventWithEventName:@"extract_completed" callbackActionFn:^(NSString* information) {
178    NSLog(@"Time to detect I2P version in install directory");
179    [self.swiftRuntime findInstalledI2PVersion];
180  }];
181 
182  //struct stat sb;
183  //if ( !(stat(i2pBaseDir.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) )
184  BOOL shouldBeTrueOnReturnDir = YES;
185  if (! [NSFileManager.defaultManager fileExistsAtPath: nsI2PBaseStr isDirectory: &shouldBeTrueOnReturnDir])
186  {
187    // I2P is not extracted.
188    if (shouldBeTrueOnReturnDir) {
189      if (self.enableVerboseLogging) NSLog(@"I2P Directory don't exists!");
190      [routerStatus triggerEventWithEn:@"router_must_upgrade" details:@"deploy needed"];
191    } else {
192      // TODO: handle if i2p path exists but it's not a dir.
193    }
194  } else {
195    // I2P was already found extracted
196    NSString *nsI2pJar = [NSString stringWithFormat:@"%@/lib/i2p.jar", nsI2PBaseStr];
197   
198    // But does I2PBASE/lib/i2p.jar exists?
199    if ([NSFileManager.defaultManager fileExistsAtPath:nsI2pJar]) {
200      NSLog(@"Time to detect I2P version in install directory");
201      [self.swiftRuntime findInstalledI2PVersion];
202    } else {
203      // The directory exists, but not i2p.jar - most likely we're in mid-extraction state.
204      [routerStatus triggerEventWithEn:@"router_must_upgrade" details:@"deploy needed"];
205    }
206  }
207 
208#endif
209}
210
211/**
212 *
213 * Exit sequence
214 *
215 **/
216- (void)applicationWillTerminate:(NSNotification *)aNotification {
217  // Tear down here
218  [self.swiftRuntime applicationWillTerminate];
219  NSString *string = @"applicationWillTerminate executed";
220  NSLog(@"%@", string);
221  [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:nil];
222}
223
224
225/* wrapper for main */
226- (AppDelegate *)initWithArgc:(int)argc argv:(const char **)argv {
227  return self;
228}
229@end
230
231#ifdef __cplusplus
232namespace {
233  const std::string logDirectory = getDefaultLogDir();
234}
235#endif
236
237int main(int argc, const char **argv)
238{
239  NSApplication *app = [NSApplication sharedApplication];
240
241#ifdef __cplusplus
242  mkdir(logDirectory.c_str(), S_IRUSR | S_IWUSR | S_IXUSR);
243 
244  SharedLogWorker logger("I2PLauncher", logDirectory);
245  MeehLog::initializeLogging(&logger);
246 
247  MLOG(INFO) << "Application is starting up";
248#endif
249 
250  AppDelegate *appDelegate = [[AppDelegate alloc] initWithArgc:argc argv:argv];
251  app.delegate = appDelegate;
252  auto mainBundle = [NSBundle mainBundle];
253  NSString* stringNameBundle = [mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey];
254  if ([[NSRunningApplication runningApplicationsWithBundleIdentifier:[mainBundle bundleIdentifier]] count] > 1) {
255    [[NSAlert alertWithMessageText:[NSString stringWithFormat:@"Another copy of %@ is already running.",stringNameBundle]
256                     defaultButton:nil alternateButton:nil otherButton:nil informativeTextWithFormat:@"This copy will now quit."] runModal];
257   
258    [NSApp terminate:nil];
259  }
260#pragma GCC diagnostic push
261#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
262  [NSBundle loadNibNamed:@"I2Launcher" owner:NSApp];
263#pragma GCC diagnostic pop
264 
265  [NSApp run];
266  return 0;
267}
268
269
270
Note: See TracBrowser for help on using the repository browser.