Changeset e8decff5 for launchers


Ignore:
Timestamp:
Sep 20, 2018 3:20:39 AM (19 months ago)
Author:
meeh <meeh@…>
Branches:
master
Children:
85ebb2f
Parents:
3c0a8cf
Message:

Mac OS X Launcher: more cleanup and some bugfixes.

Location:
launchers/macosx
Files:
1 deleted
7 edited

Legend:

Unmodified
Added
Removed
  • launchers/macosx/AppDelegate.h

    r3c0a8cf re8decff5  
    1414
    1515#include <Cocoa/Cocoa.h>
     16#include "SBridge.h"
    1617
    1718
    1819#include "RouterTask.h"
    19 #include "JavaHelper.h"
    2020
    2121
     
    3434
    3535@class ExtractMetaInfo;
    36 
    37 
    3836
    3937@interface ExtractMetaInfo : NSObject
     
    6462}
    6563
    66 inline void sendUserNotification(NSString* title, NSString* informativeText, NSImage* contentImage = NULL, bool makeSound = false) {
     64inline void sendUserNotification(NSString* title, NSString* informativeText, bool makeSound = false) {
    6765  NSUserNotification *userNotification = [[NSUserNotification alloc] init];
    6866 
     
    8179};
    8280
    83 using maybeAnRouterRunner = I2PRouterTask*;
    84 
    85 std::vector<std::string> buildClassPath(std::string basePath);
    86 
    87 extern JvmListSharedPtr gRawJvmList;
    88 
    89 // DO NOT ACCESS THIS GLOBAL VARIABLE DIRECTLY.
    90 static std::mutex globalRouterStatusMutex;
    91 static maybeAnRouterRunner globalRouterStatus = maybeAnRouterRunner{};
    92 static bool isRuterRunning = false;
    93 
    94 maybeAnRouterRunner getGlobalRouterObject();
    95 void setGlobalRouterObject(I2PRouterTask* newRouter);
    96 bool getGlobalRouterIsRunning();
    97 void setGlobalRouterIsRunning(bool running);
    98 
    99 #include "SBridge.h"
    100 
    10181#endif
    10282
    103 @class MenuBarCtrl;
    104 
    105 @interface AppDelegate : NSObject <NSUserNotificationCenterDelegate, NSApplicationDelegate> {
    106 @public
    107   //NSImageView *imageCell;
    108 }
     83@interface AppDelegate : NSObject <NSUserNotificationCenterDelegate, NSApplicationDelegate>
    10984@property BOOL enableLogging;
    11085@property BOOL enableVerboseLogging;
     
    11994- (void) applicationWillTerminate:(NSNotification *)aNotification;
    12095- (void) setApplicationDefaultPreferences;
    121 - (void) userChooseJavaHome;
    12296- (AppDelegate *) initWithArgc:(int)argc argv:(const char **)argv;
    123 #ifdef __cplusplus
    124 - (void) startupI2PRouter;
    125 - (NSString *) userSelectJavaHome:(JvmListPtr)rawJvmList;
    126 #endif
    12797- (BOOL) userNotificationCenter:(NSUserNotificationCenter *)center
    12898                               shouldPresentNotification:(NSUserNotification *)notification;
  • launchers/macosx/I2PLauncher/routermgmt/RouterProcessStatus.swift

    r3c0a8cf re8decff5  
    2727 
    2828  @objc func getRouterIsRunning() -> Bool {
    29     if (RouterProcessStatus.isRouterRunning) {
    30       return false;
    31     } else {
    32       let running: Bool = RouterProcessStatus.isRouterRunning
    33       return running
    34     }
     29    return RouterProcessStatus.isRouterRunning
    3530  }
    3631 
    3732  @objc func getJavaHome() -> String {
    3833    return RouterProcessStatus.knownJavaBinPath!
    39   }
    40  
    41   @objc func setJavaHome(_ home: String) {
    42     NSLog("Setting known java to %s", home)
    43     RouterProcessStatus.knownJavaBinPath = home
    4434  }
    4535}
     
    4939  static var isRouterChildProcess : Bool = false
    5040  static var routerVersion : String? = Optional.none
    51   static var routerUptime : String? = Optional.none
     41  static var routerUptime : String? = Optional.none{
     42    //Called before the change
     43    willSet(newValue){
     44      print("RouterProcessStatus.routerUptime will change from ", (self.routerUptime ?? "nil"), " to "+(newValue ?? "nil"))
     45    }
     46   
     47    //Called after the change
     48    didSet{
     49      print("RouterProcessStatus.routerUptime did change to "+self.routerUptime!)
     50    }
     51  }
    5252  static var routerStartedAt : Date? = Optional.none
    5353  static var knownJavaBinPath : String? = Optional.none
  • launchers/macosx/RouterTask.h

    r3c0a8cf re8decff5  
    33#include <dispatch/dispatch.h>
    44#include <memory.h>
    5 #include <string.h>
    65
    76#include <Cocoa/Cocoa.h>
     
    98
    109#ifdef __cplusplus
    11 #include "include/subprocess.hpp"
    12 
    13 using namespace subprocess;
    14 class JavaRunner;
    15 
    16 typedef std::function<void(void)> fp_t;
    17 typedef std::function<void(JavaRunner *ptr)> fp_proc_t;
     10#include <vector>
     11#include <string>
    1812
    1913const std::vector<NSString*> defaultStartupFlags {
     
    3125  "-Xms128m",
    3226  "-Djava.awt.headless=true"
    33 };
    34 
    35 /**
    36  *
    37  * class JavaRunner
    38  *
    39  **/
    40 class JavaRunner
    41 {
    42 public:
    43   // copy fn
    44   JavaRunner(std::string& javaBin, std::string& arguments, std::string& i2pBaseDir, const fp_proc_t& executingFn, const fp_t& cb);
    45   ~JavaRunner() = default;
    46  
    47   void requestRouterShutdown();
    48  
    49   std::future<int> execute();
    50   std::shared_ptr<subprocess::Popen> javaProcess;
    51   std::string javaBinaryPath;
    52   std::string javaRouterArgs;
    53   std::string execLine;
    54   std::string _i2pBaseDir;
    55 private:
    56   const fp_proc_t& executingFn;
    57   const fp_t& exitCallbackFn;
    5827};
    5928
  • launchers/macosx/RouterTask.mm

    r3c0a8cf re8decff5  
    1010#include "AppDelegate.h"
    1111#endif
     12
    1213#include "include/PidWatcher.h"
    1314
     
    5354
    5455  [self.routerTask setTerminationHandler:^(NSTask* task) {
     56    // Cleanup
    5557    NSLog(@"termHandler triggered!");
    5658    auto swiftRouterStatus = [[RouterProcessStatus alloc] init];
    57     [swiftRouterStatus setRouterStatus: true];
     59    [swiftRouterStatus setRouterStatus: false];
     60    [swiftRouterStatus setRouterRanByUs: false];
    5861    sendUserNotification(APP_IDSTR, @"I2P Router has stopped");
    59     // Cleanup
    60     //self.isRouterRunning = NO;
    6162  }];
    62 /*
    63     self.readLogHandle = [self.processPipe fileHandleForReading];
    64     NSData *inData = nil;
    65     self.totalLogData = [[[NSMutableData alloc] init] autorelease];
    66 
    67     while ((inData = [self.readLogHandle availableData]) &&
    68         [inData length]) {
    69         [self.totalLogData appendData:inData];
    70     }
    71 */
    7263    return self;
    7364}
     
    9283{
    9384    @try {
    94         [self.routerTask launch];
    95         watchPid([self.routerTask processIdentifier]);
    96         self.isRouterRunning = YES;
    97         return 1;
     85      [self.routerTask launch];
     86      watchPid([self.routerTask processIdentifier]);
     87      self.isRouterRunning = YES;
     88      return 1;
    9889    }
    9990    @catch (NSException *e)
    10091        {
    10192                NSLog(@"Expection occurred %@", [e reason]);
    102         return 0;
     93    auto swiftRouterStatus = [[RouterProcessStatus alloc] init];
     94    [swiftRouterStatus setRouterStatus: false];
     95    [swiftRouterStatus setRouterRanByUs: false];
     96    sendUserNotification(@"An error occured, can't start the I2P Router", [e reason]);
     97    return 0;
    10398        }
    10499}
     
    106101- (int) getPID
    107102{
    108     return [self.routerTask processIdentifier];
     103  return [self.routerTask processIdentifier];
    109104}
    110105
    111106@end
    112 
    113 #ifdef __cplusplus
    114 
    115 JavaRunner::JavaRunner(std::string& javaBin, std::string& arguments, std::string& i2pBaseDir, const fp_proc_t& execFn, const fp_t& cb)
    116   : javaBinaryPath(javaBin), javaRouterArgs(arguments), _i2pBaseDir(i2pBaseDir), executingFn(execFn), exitCallbackFn(cb)
    117 {
    118   execLine = javaBinaryPath;
    119   execLine += " " + std::string(javaRouterArgs.c_str());
    120   printf("CLI: %s\n",execLine.c_str());
    121   javaProcess = std::shared_ptr<Popen>(new Popen(execLine, environment{{
    122             {"I2PBASE", _i2pBaseDir},
    123             {"JAVA_OPTS", getenv("JAVA_OPTS")}
    124         }}, defer_spawn{true}));
    125 }
    126 
    127 void JavaRunner::requestRouterShutdown()
    128 {
    129     // SIGHUP
    130     javaProcess->kill(1);
    131 }
    132 
    133 std::future<int> JavaRunner::execute()
    134 {
    135   try {
    136     auto executingFn = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, ^{
    137       this->executingFn(this);
    138     });
    139     dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), executingFn);
    140     dispatch_block_wait(executingFn, DISPATCH_TIME_FOREVER);
    141 
    142     // Here, the process is done executing.
    143 
    144     printf("Finished executingFn - Runs callbackFn\n");
    145     this->exitCallbackFn();
    146     return std::async(std::launch::async, []{ return 0; });
    147   } catch (std::exception* ex) {
    148     printf("ERROR: %s\n", ex->what());
    149     return std::async(std::launch::async, []{ return 1; });
    150   }
    151 }
    152 
    153 #endif
  • launchers/macosx/SBridge.h

    r3c0a8cf re8decff5  
    88
    99#import <Foundation/Foundation.h>
     10#import <Cocoa/Cocoa.h>
     11
     12#ifdef __cplusplus
     13#include <memory>
     14#include <future>
     15#include <glob.h>
     16#include <string>
     17#include <vector>
     18#include "include/fn.h"
     19std::future<int> startupRouter(NSString* javaBin, NSArray<NSString*>* arguments, NSString* i2pBaseDir);
     20
     21
     22namespace osx {
     23  inline void openUrl(NSString* url)
     24  {
     25    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString: url]];
     26  }
     27}
     28
     29inline std::vector<std::string> globVector(const std::string& pattern){
     30  glob_t glob_result;
     31  glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);
     32  std::vector<std::string> files;
     33  for(unsigned int i=0;i<glob_result.gl_pathc;++i){
     34    files.push_back(std::string(glob_result.gl_pathv[i]));
     35  }
     36  globfree(&glob_result);
     37  return files;
     38}
     39
     40inline std::string buildClassPathForObjC(std::string basePath)
     41{
     42  NSBundle *launcherBundle = [NSBundle mainBundle];
     43  auto jarList = globVector(basePath+std::string("/lib/*.jar"));
     44 
     45  std::string classpathStrHead = "-classpath";
     46  std::string classpathStr = "";
     47  classpathStr += [[launcherBundle pathForResource:@"launcher" ofType:@"jar"] UTF8String];
     48  std::string prefix(basePath);
     49  prefix += "/lib/";
     50  for_each(jarList, [&classpathStr](std::string str){ classpathStr += std::string(":") + str; });
     51  return classpathStr;
     52}
     53
     54#endif
    1055
    1156@interface SBridge : NSObject
  • launchers/macosx/SBridge.mm

    r3c0a8cf re8decff5  
    3434    options.i2pBaseDir = i2pBaseDir;
    3535    auto instance = [[I2PRouterTask alloc] initWithOptions: options];
    36     //setGlobalRouterObject(instance);
    37     //NSThread *thr = [[NSThread alloc] initWithTarget:instance selector:@selector(execute) object:nil];
    3836    [instance execute];
    3937    sendUserNotification(APP_IDSTR, @"The I2P router is starting up.");
     
    5452}
    5553
    56 namespace osx {
    57   inline void openUrl(NSString* url)
    58   {
    59     [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString: url]];
    60   }
    61 }
    62 
    63 inline std::vector<std::string> globVector(const std::string& pattern){
    64   glob_t glob_result;
    65   glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);
    66   std::vector<std::string> files;
    67   for(unsigned int i=0;i<glob_result.gl_pathc;++i){
    68     files.push_back(std::string(glob_result.gl_pathv[i]));
    69   }
    70   globfree(&glob_result);
    71   return files;
    72 }
    73 
    74 inline std::string buildClassPathForObjC(std::string basePath)
    75 {
    76   NSBundle *launcherBundle = [NSBundle mainBundle];
    77   auto jarList = globVector(basePath+std::string("/lib/*.jar"));
    78  
    79   std::string classpathStrHead = "-classpath";
    80   std::string classpathStr = "";
    81   classpathStr += [[launcherBundle pathForResource:@"launcher" ofType:@"jar"] UTF8String];
    82   std::string prefix(basePath);
    83   prefix += "/lib/";
    84   for_each(jarList, [&classpathStr](std::string str){ classpathStr += std::string(":") + str; });
    85   return classpathStr;
    86 }
    8754
    8855
  • launchers/macosx/main.mm

    r3c0a8cf re8decff5  
    1212#import <Foundation/Foundation.h>
    1313#import <Foundation/NSFileManager.h>
    14 
    15 
    16 #include <CoreFoundation/CoreFoundation.h>
    17 #include <CoreFoundation/CFStream.h>
    18 #include <CoreFoundation/CFPropertyList.h>
    19 #include <CoreFoundation/CFDictionary.h>
    20 #include <CoreFoundation/CFArray.h>
    21 #include <CoreFoundation/CFString.h>
    2214#include <CoreFoundation/CFPreferences.h>
    2315
     
    3123#include "AppDelegate.h"
    3224#include "RouterTask.h"
    33 #include "JavaHelper.h"
    3425#include "include/fn.h"
    3526#include "include/portcheck.h"
     
    112103      cli.push_back("net.i2p.launchers.BaseExtractor");
    113104      auto rs = [[RouterProcessStatus alloc] init];
    114       NSString* jh = [rs getJavaHome];
    115       if (jh != nil) {
    116         NSLog(@"jh er %@", jh);
    117       }
    118      
    119       NSString* newString = [NSString stringWithFormat:@"file://%@", rs.getJavaHome];
    120       NSURL *baseURL = [NSURL fileURLWithPath:newString];
    121105     
    122106      std::string execStr = std::string([rs.getJavaHome UTF8String]);
     
    133117        if (extractStatus == 0)
    134118        {
    135           //success = YES;
    136           NSLog(@"Time to detect I2P version in install directory");
    137           [self.swiftRuntime findInstalledI2PVersion];
     119          NSLog(@"Extraction complete!");
    138120        }
    139121     
     
    147129      // All done. Assume success and error are already set.
    148130      dispatch_async(dispatch_get_main_queue(), ^{
    149         //sendUserNotification(APP_IDSTR, @"Extraction complete!", self.contentImage);
    150131        if (completion) {
    151132          completion(success, error);
     
    159140    }
    160141  });
    161    
    162  
    163 }
    164 
    165 
    166 - (NSString *)userSelectJavaHome:(JvmListPtr)rawJvmList
    167 {
    168   NSString *appleScriptString = @"set jvmlist to {\"Newest\"";
    169   for (auto item : *rawJvmList) {
    170     auto str = strprintf(",\"%s\"", item->JVMName.c_str()).c_str();
    171     NSString* tmp = [NSString stringWithUTF8String:str];
    172     appleScriptString = [appleScriptString stringByAppendingString:tmp];
    173   }
    174   appleScriptString = [appleScriptString stringByAppendingString:@"}\nchoose from list jvmlist\n"];
    175   NSAppleScript *theScript = [[NSAppleScript alloc] initWithSource:appleScriptString];
    176   NSDictionary *theError = nil;
    177   NSString* userResult = [[theScript executeAndReturnError: &theError] stringValue];
    178   NSLog(@"User choosed %@.\n", userResult);
    179   if (theError != nil)
    180   {
    181     NSLog(@"Error: %@.\n", theError);
    182   }
    183   return userResult;
    184142}
    185143
    186144- (void)setApplicationDefaultPreferences {
    187   auto defaultJVMHome = check_output({"/usr/libexec/java_home","-v",DEF_MIN_JVM_VER});
    188   auto tmpStdStr = std::string(defaultJVMHome.buf.data());
    189   trim(tmpStdStr);
    190   auto cfDefaultHome  = CFStringCreateWithCString(NULL, const_cast<const char *>(tmpStdStr.c_str()), kCFStringEncodingUTF8);
    191145  [self.userPreferences registerDefaults:@{
    192     @"javaHome" : (NSString *)cfDefaultHome,
    193     @"lastI2PVersion" : (NSString *)CFSTR(DEF_I2P_VERSION),
    194146    @"enableLogging": @YES,
    195147    @"enableVerboseLogging": @YES,
     
    197149    @"i2pBaseDirectory": (NSString *)CFStringCreateWithCString(NULL, const_cast<const char *>(getDefaultBaseDir().c_str()), kCFStringEncodingUTF8)
    198150  }];
    199   if (self.enableVerboseLogging) NSLog(@"Default JVM home preference set to: %@", cfDefaultHome);
    200151
    201152  auto dict = [self.userPreferences dictionaryRepresentation];
     
    206157
    207158  if (self.enableVerboseLogging) NSLog(@"Default preferences stored!");
     159}
     160
    208161#endif
    209 }
    210 
    211 
    212162
    213163
     
    232182
    233183#ifdef __cplusplus
    234   //gRawJvmList = std::make_shared<std::list<JvmVersionPtr> >(std::list<JvmVersionPtr>());
    235184
    236185  RouterProcessStatus* routerStatus = [[RouterProcessStatus alloc] init];
     
    256205
    257206  NSBundle *launcherBundle = [NSBundle mainBundle];
     207  auto sBridge = [[SBridge alloc] init];
    258208 
    259209  // Helper object to hold statefull path information
     
    270220  jarfile += [self.metaInfo.zipFile UTF8String];
    271221 
    272   auto sBridge = [[SBridge alloc] init];
    273  
    274222  // Initialize the Swift environment (the UI components)
    275223  [self.swiftRuntime applicationDidFinishLaunching];
     
    287235      NSLog(@"Done extracting I2P");
    288236     
     237      NSLog(@"Time to detect I2P version in install directory");
     238      [self.swiftRuntime findInstalledI2PVersion];
    289239      if (shouldAutoStartRouter) {
    290240        [sBridge startupI2PRouter:self.metaInfo.i2pBase javaBinPath:self.metaInfo.javaBinary];
     
    295245  } else {
    296246    // I2P was already found extracted
     247    NSLog(@"Time to detect I2P version in install directory");
     248    [self.swiftRuntime findInstalledI2PVersion];
    297249   
    298250    if (shouldAutoStartRouter) {
Note: See TracChangeset for help on using the changeset viewer.