Ignore:
Timestamp:
Jul 24, 2018 4:26:40 PM (2 years ago)
Author:
meeh <meeh@…>
Branches:
master
Children:
7338282b
Parents:
2ee1a21
Message:

Code changes:

  • Port check to see if i2p is already running.
  • All buttons in the menu should work now.
  • Rewrote some C++ to Objective-C, which fits better with the integration.
  • Misc cleanup.
  • Made the launch of router repeatable.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • launchers/macosx/obj-cpp/main.mm

    r2ee1a21 rf9fbc76  
    3131#include "fn.h"
    3232#include "optional.hpp"
     33#include "portcheck.h"
    3334
    3435#define debug(format, ...) CFShow([NSString stringWithFormat:format, ## __VA_ARGS__]);
     
    4344@end
    4445
     46std::vector<std::string> buildClassPath(std::string basePath)
     47{
     48    return globVector(basePath+std::string("/lib/*.jar"));
     49}
    4550
    4651maybeAnRouterRunner getGlobalRouterObject()
     
    5055}
    5156
    52 void setGlobalRouterObject(RouterTask* newRouter)
     57void setGlobalRouterObject(I2PRouterTask* newRouter)
    5358{
    5459    std::lock_guard<std::mutex> lock(globalRouterStatusMutex);
     
    5661}
    5762
     63
     64pthread_mutex_t mutex;
     65
     66bool getGlobalRouterIsRunning()
     67{
     68    pthread_mutex_lock(&mutex);
     69    bool current = isRuterRunning;
     70    pthread_mutex_unlock(&mutex);
     71    return current;
     72}
     73void setGlobalRouterIsRunning(bool running)
     74{
     75    pthread_mutex_lock(&mutex);
     76    isRuterRunning = running;
     77    pthread_mutex_unlock(&mutex);
     78}
     79
    5880std::future<int> startupRouter(NSString* javaBin, NSArray<NSString*>* arguments, NSString* i2pBaseDir) {
    59 /*
    60   NSLog(@"Arguments: %@", [NSString stringWithUTF8String:arguments.c_str()]);
    61   auto launchLambda = [](JavaRunner *javaRun) {
    62     javaRun->javaProcess->start_process();
    63     auto pid = javaRun->javaProcess->pid();
    64     std::cout << "I2P Router process id = " << pid << std::endl;
    65 
    66     // Blocking
    67     javaRun->javaProcess->wait();
    68   };
    69   auto callbackAfterExit = [](){
    70     printf("Callback after exit\n");
    71   };
    72   NSLog(@"Still fine!");
    73 
    74   setGlobalRouterObject(new JavaRunner{ javaBin, arguments, i2pBaseDir, std::move(launchLambda), std::move(callbackAfterExit) });
    75 
    76   NSLog(@"Still fine!");
    77   return std::async(std::launch::async, [&]{
    78       getGlobalRouterObject().value()->execute();
    79       return 0;
    80     });
    81 */
    82     //CFShow(arguments);
    83 
    8481    @try {
    8582        RTaskOptions* options = [RTaskOptions alloc];
     
    8784        options.arguments = arguments;
    8885        options.i2pBaseDir = i2pBaseDir;
    89         auto instance = [[[RouterTask alloc] initWithOptions: options] autorelease];
     86        auto instance = [[[I2PRouterTask alloc] initWithOptions: options] autorelease];
    9087        setGlobalRouterObject(instance);
    9188        //NSThread *thr = [[NSThread alloc] initWithTarget:instance selector:@selector(execute) object:nil];
     
    113110}
    114111
     112@implementation I2PStatusMenu
     113
     114- (BOOL)validateMenuItem:(NSMenuItem *)item
     115{
     116  NSLog(@"item is: %@",item);
     117  return YES;
     118}
     119
     120@end
    115121
    116122@implementation MenuBarCtrl
     
    149155{
    150156  NSLog(@"Clicked startJavaRouterBtnHandler");
     157  AppDelegate *appDelegate = (AppDelegate *)[[NSApplication sharedApplication] delegate];
     158  [appDelegate startupI2PRouter];
    151159}
    152160
     
    211219}
    212220
    213 - (NSMenu *)createStatusBarMenu
    214 {
    215   NSMenu *menu = [[NSMenu alloc] init];
     221- (I2PStatusMenu *)createStatusBarMenu
     222{
     223  I2PStatusMenu *menu = [[I2PStatusMenu alloc] init];
    216224  [menu setAutoenablesItems:NO];
    217225
     
    272280@implementation AppDelegate
    273281
    274 - (void)extractI2PBaseDir:(ExtractMetaInfo *)metaInfo completion:(void(^)(BOOL success, NSError *error))completion
    275 {
    276   std::string basePath([metaInfo.i2pBase UTF8String]);
    277   NSParameterAssert(metaInfo.i2pBase);
     282- (void)extractI2PBaseDir:(void(^)(BOOL success, NSError *error))completion
     283{
     284  std::string basePath([self.metaInfo.i2pBase UTF8String]);
     285  NSParameterAssert(self.metaInfo.i2pBase);
    278286  NSError *error = NULL;
    279287  BOOL success;
     
    287295
    288296    std::string zippath("-Di2p.base.zip=");
    289     zippath += [metaInfo.zipFile UTF8String];
     297    zippath += [self.metaInfo.zipFile UTF8String];
    290298
    291299    std::string jarfile("-cp ");
    292     jarfile += [metaInfo.jarFile UTF8String];
     300    jarfile += [self.metaInfo.jarFile UTF8String];
    293301
    294302    // Create directory
     
    306314
    307315    //auto charCli = map(cli, [](std::string str){ return str.c_str(); });
    308     std::string execStr = [metaInfo.javaBinary UTF8String];
     316    std::string execStr = [self.metaInfo.javaBinary UTF8String];
    309317    for_each(cli, [&execStr](std::string str){ execStr += std::string(" ") + str; });
    310318
     
    338346}
    339347
    340 - (void)startupI2PRouter:(ExtractMetaInfo *)metaInfo
    341 {
    342   std::string basePath([metaInfo.i2pBase UTF8String]);
    343   auto buildClassPath = [](std::string basePath) -> std::vector<std::string> {
    344       return globVector(basePath+std::string("/lib/*.jar"));
    345   };
    346     // Expect base to be extracted by now.
    347 
    348     // Get paths
    349     NSBundle *launcherBundle = [NSBundle mainBundle];
     348- (void)startupI2PRouter
     349{
     350  std::string basePath([self.metaInfo.i2pBase UTF8String]);
     351
     352  // Get paths
     353  NSBundle *launcherBundle = [NSBundle mainBundle];
    350354  auto jarList = buildClassPath(basePath);
    351355  std::string classpathStrHead = "-classpath";
     
    372376    argList.push_back([NSString stringWithUTF8String:classpathStr.c_str()]);
    373377    argList.push_back(@"net.i2p.router.Router");
    374     auto javaBin = std::string([metaInfo.javaBinary UTF8String]);
     378    auto javaBin = std::string([self.metaInfo.javaBinary UTF8String]);
    375379
    376380
    377381    sendUserNotification(APP_IDSTR, @"I2P Router is starting up!", self.contentImage);
    378     auto nsJavaBin = metaInfo.javaBinary;
    379     auto nsBasePath = metaInfo.i2pBase;
     382    auto nsJavaBin = self.metaInfo.javaBinary;
     383    auto nsBasePath = self.metaInfo.i2pBase;
    380384    NSArray* arrArguments = [NSArray arrayWithObjects:&argList[0] count:argList.size()];
    381385    startupRouter(nsJavaBin, arrArguments, nsBasePath);
     
    435439    @"enableLogging": @true,
    436440    @"enableVerboseLogging": @true,
    437     @"autoStartRouter": @true
     441    @"autoStartRouter": @true,
     442    @"i2pBaseDirectory": (NSString *)CFStringCreateWithCString(NULL, const_cast<const char *>(getDefaultBaseDir().c_str()), kCFStringEncodingUTF8)
    438443  }];
    439444  if (self.enableVerboseLogging) NSLog(@"Default JVM home preference set to: %@", (NSString *)cfDefaultHome);
     
    469474  [NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];
    470475  [NSApp activateIgnoringOtherApps:YES];
    471   //auto prefArray = CFPreferencesCopyKeyList(CFAPPDOMAIN, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
    472   //CFShow(prefArray);
    473476  auto javaHomePref = [self.userPreferences stringForKey:@"javaHome"];
    474477  if (self.enableVerboseLogging) NSLog(@"Java home from preferences: %@", javaHomePref);
    475478
    476 
    477479  // This is the only GUI the user experience on a regular basis.
    478480  self.menuBarCtrl = [[MenuBarCtrl alloc] init];
     
    483485  NSLog(@"We should have started the statusbar object by now...");
    484486
    485   // Figure out base directory
    486   const char* pathFromHome = "/Users/%s/Library/I2P";
    487   auto username = getenv("USER");
    488   char buffer[strlen(pathFromHome)+strlen(username)];
    489   sprintf(buffer, pathFromHome, username);
    490   std::string i2pBaseDir(buffer);
    491   if (self.enableVerboseLogging) printf("Home directory is: %s\n", buffer);
     487  std::string i2pBaseDir(getDefaultBaseDir());
     488  //if (self.enableVerboseLogging) printf("Home directory is: %s\n", buffer);
    492489
    493490
     
    500497  self.menuBarCtrl.enableVerboseLogging = self.enableVerboseLogging;
    501498
     499
     500
     501  if (port_check() != 0)
     502  {
     503    NSLog(@"Seems i2p is already running - I will not start the router (port 7657 is in use..)");
     504    return;
     505  }
     506
    502507  if (self.enableVerboseLogging) NSLog(@"processinfo %@", [[NSProcessInfo processInfo] arguments]);
    503508
    504   auto getJavaHomeLambda = [&pref,&self]() -> std::string {
    505       NSString* val = @"";
    506       val = [pref stringForKey:@"javaHome"];
    507       if (val == NULL) val = @"";
    508       if (self.enableVerboseLogging) NSLog(@"Javahome: %@", val);
    509       return std::string([val UTF8String]);;
    510   };
    511 
    512   auto getJavaBin = [&getJavaHomeLambda]() -> std::string {
    513       // Get Java home
    514     auto javaHome = getJavaHomeLambda();
     509  auto getJavaBin = [&pref,&self]() -> std::string {
     510    // Get Java home
     511    NSString* val = @"";
     512    val = [pref stringForKey:@"javaHome"];
     513    if (val == NULL) val = @"";
     514    if (self.enableVerboseLogging) NSLog(@"Javahome: %@", val);
     515    auto javaHome = std::string([val UTF8String]);
    515516    trim(javaHome); // Trim to remove endline
    516517    auto javaBin = std::string(javaHome);
     
    519520  };
    520521
    521   auto buildClassPath = [](std::string basePath) -> std::vector<std::string> {
    522       return globVector(basePath+std::string("/lib/*.jar"));
    523   };
    524 
    525 
    526   auto metaInfo = [ExtractMetaInfo alloc];
    527   metaInfo.i2pBase = [NSString stringWithUTF8String:buffer];
    528   metaInfo.javaBinary = [NSString stringWithUTF8String:getJavaBin().c_str()];
    529   metaInfo.jarFile = [launcherBundle pathForResource:@"launcher" ofType:@"jar"];
    530   metaInfo.zipFile = [launcherBundle pathForResource:@"base" ofType:@"zip"];
     522
     523  self.metaInfo = [[ExtractMetaInfo alloc] init];
     524  self.metaInfo.i2pBase = [NSString stringWithUTF8String:i2pBaseDir.c_str()];
     525  self.metaInfo.javaBinary = [NSString stringWithUTF8String:getJavaBin().c_str()];
     526  self.metaInfo.jarFile = [launcherBundle pathForResource:@"launcher" ofType:@"jar"];
     527  self.metaInfo.zipFile = [launcherBundle pathForResource:@"base" ofType:@"zip"];
    531528
    532529  std::string basearg("-Di2p.dir.base=");
     
    534531
    535532  std::string jarfile("-cp ");
    536   jarfile += [metaInfo.zipFile UTF8String];
     533  jarfile += [self.metaInfo.zipFile UTF8String];
    537534
    538535  struct stat sb;
    539   if ( !(stat(buffer, &sb) == 0 && S_ISDIR(sb.st_mode)) )
     536  if ( !(stat(i2pBaseDir.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) )
    540537  {
    541538    // I2P is not extracted.
    542539    if (self.enableVerboseLogging) NSLog(@"I2P Directory don't exists!");
    543540
    544     [self extractI2PBaseDir: metaInfo completion:^(BOOL success, NSError *error) {
     541    [self extractI2PBaseDir:^(BOOL success, NSError *error) {
    545542        //__typeof__(self) strongSelf = weakSelf;
    546543        //if (strongSelf == nil) return;
    547         [self startupI2PRouter:metaInfo];
     544        [self startupI2PRouter];
    548545    }];
    549546
    550547  } else {
    551548      if (self.enableVerboseLogging) NSLog(@"I2P directory found!");
    552       [self startupI2PRouter:metaInfo];
     549      [self startupI2PRouter];
    553550  }
    554551
Note: See TracChangeset for help on using the changeset viewer.