Changeset 3c0a8cf


Ignore:
Timestamp:
Sep 20, 2018 2:38:44 AM (21 months ago)
Author:
meeh <meeh@…>
Branches:
master
Children:
e8decff5
Parents:
eb81cada
Message:

Mac OSX Launcher: A lot of bugfixes, refactoring and cleanup.

Location:
launchers/macosx
Files:
9 edited

Legend:

Unmodified
Added
Removed
  • launchers/macosx/I2PLauncher/SwiftMainDelegate.swift

    reb81cada r3c0a8cf  
    1414  //let statusItem = NSStatusBar.system().statusItem(withLength: NSSquareStatusItemLength )
    1515  let statusBarController = StatusBarController()
    16   let javaDetector = DetectJava()
     16  static let javaDetector = DetectJava()
    1717  static let objCBridge = SBridge()
    1818 
    1919  override init() {
    2020    super.init()
    21    
    22     self.javaDetector.findIt()
    23     if (!javaDetector.isJavaFound()) {
    24       print("Could not find java....")
    25       terminate("No java..")
     21    if (!SwiftMainDelegate.javaDetector.isJavaFound()) {
     22    SwiftMainDelegate.javaDetector.findIt()
     23      if (!SwiftMainDelegate.javaDetector.isJavaFound()) {
     24        print("Could not find java....")
     25        terminate("No java..")
     26      }
    2627    }
    27     let javaBinPath = self.javaDetector.javaHome
     28    let javaBinPath = SwiftMainDelegate.javaDetector.javaHome
    2829    RouterProcessStatus.knownJavaBinPath = javaBinPath
    2930    print("Found java home = ", javaBinPath)
     
    7879    i2pPath += "/Library/I2P"
    7980   
    80     //let javaBinPath = self.javaDetector.javaHome.replace(target: " ", withString: "\\ ")
    81    
    8281    let fileManager = FileManager()
    8382    var ok = ObjCBool(true)
  • launchers/macosx/I2PLauncher/routermgmt/DetectJava.swift

    reb81cada r3c0a8cf  
    1111@objc class DetectJava : NSObject {
    1212 
    13   var hasJRE : Bool = false
    14   var userWantJRE : Bool = false
    15   var userAcceptOracleEULA : Bool = false
     13  static var hasJRE : Bool = false
     14  static var userWantJRE : Bool = false
     15  static var userAcceptOracleEULA : Bool = false
    1616 
    1717 
     
    3030    //Called after the change
    3131    didSet{
    32       hasJRE = true
    33       print("DetectJava.javaHome did change from "+oldValue+" to "+self.javaHome)
     32      DetectJava.hasJRE = true
     33      self.javaHome = self.javaHome.replace(target: "\n", withString: "").replace(target: "Internet Plug-Ins", withString: "Internet\\ Plug-Ins")
     34      print("DetectJava.javaHome did change to "+self.javaHome)
    3435    }
    3536  };
     
    5152   **/
    5253  @objc func findIt() {
     54    if (DetectJava.hasJRE) {
     55      return
     56    }
    5357    print("Start with checking environment variable")
    5458    self.checkJavaEnvironmentVariable()
    5559    if !(self.javaHome.isEmpty) {
    5660      RouterProcessStatus.knownJavaBinPath = Optional.some(self.javaHome)
    57       hasJRE = true
     61      DetectJava.hasJRE = true
    5862      return
    5963    }
     
    6266    if !(self.javaHome.isEmpty) {
    6367      RouterProcessStatus.knownJavaBinPath = Optional.some(self.javaHome)
    64       hasJRE = true
     68      DetectJava.hasJRE = true
    6569      return
    6670    }
     
    6973    if !(self.javaHome.isEmpty) {
    7074      RouterProcessStatus.knownJavaBinPath = Optional.some(self.javaHome)
    71       hasJRE = true
     75      DetectJava.hasJRE = true
    7276      return
    7377    }
  • launchers/macosx/I2PLauncher/routermgmt/RouterProcessStatus.swift

    reb81cada r3c0a8cf  
    2727 
    2828  @objc func getRouterIsRunning() -> Bool {
    29     if (RouterProcessStatus.isRouterRunning == Optional.none) {
     29    if (RouterProcessStatus.isRouterRunning) {
    3030      return false;
    3131    } else {
  • launchers/macosx/I2PLauncher/userinterface/PopoverViewController.swift

    reb81cada r3c0a8cf  
    6161  override func viewWillDraw() {
    6262    super.viewWillDraw()
    63     if (RouterStatusView.instance == Optional.none) {
     63    if (RouterStatusView.instance != nil) {
    6464      RouterStatusView.instance = self
    6565    }
     
    7979    quickControlView?.needsDisplay = true
    8080   
    81     if (RouterProcessStatus.routerVersion == Optional.none) {
     81    if let version = RouterProcessStatus.routerVersion {
     82      routerVersionLabel?.cell?.stringValue = "Router version: " + version
     83    } else {
    8284      routerVersionLabel?.cell?.stringValue = "Router version: Still unknown"
    83       // trigger a read to ensure values
    84       let tmp = SwiftMainDelegate()
    85       tmp.findInstalledI2PVersion()
    86     } else {
    87       routerVersionLabel?.cell?.stringValue = "Router version: " + RouterProcessStatus.routerVersion!
    8885    }
    89     if (RouterProcessStatus.routerStartedAt != Optional.none) {
    90       routerUptimeLabel?.cell?.stringValue = "Router has runned for " + DateTimeUtils.timeAgoSinceDate(date: NSDate(date: RouterProcessStatus.routerStartedAt!), numericDates: false)
     86    if let routerStartTime = RouterProcessStatus.routerStartedAt {
     87      routerUptimeLabel?.cell?.stringValue = "Router has runned for " + DateTimeUtils.timeAgoSinceDate(date: NSDate(date: routerStartTime), numericDates: false)
    9188    }
    9289  }
  • launchers/macosx/Info.plist

    reb81cada r3c0a8cf  
    1010        <string>Public Domain</string>
    1111        <key>CFBundleGetInfoString</key>
    12         <string>0.9.35-experimental</string>
     12        <string>0.9.36-experimental</string>
    1313        <key>CFBundleIconFile</key>
    1414        <string>images/AppIcon.icns</string>
  • launchers/macosx/RouterTask.h

    reb81cada r3c0a8cf  
    1717typedef std::function<void(JavaRunner *ptr)> fp_proc_t;
    1818
     19const std::vector<NSString*> defaultStartupFlags {
     20  @"-Xmx512M",
     21  @"-Xms128m",
     22  @"-Djava.awt.headless=true",
     23  @"-Dwrapper.logfile=/tmp/router.log",
     24  @"-Dwrapper.logfile.loglevel=DEBUG",
     25  @"-Dwrapper.java.pidfile=/tmp/routerjvm.pid",
     26  @"-Dwrapper.console.loglevel=DEBUG"
     27};
    1928
     29const std::vector<std::string> defaultFlagsForExtractorJob {
     30  "-Xmx512M",
     31  "-Xms128m",
     32  "-Djava.awt.headless=true"
     33};
    2034
    2135/**
     
    3044  JavaRunner(std::string& javaBin, std::string& arguments, std::string& i2pBaseDir, const fp_proc_t& executingFn, const fp_t& cb);
    3145  ~JavaRunner() = default;
    32  
    33   static const std::vector<NSString*> defaultStartupFlags;
    34   static const std::vector<std::string> defaultFlagsForExtractorJob;
    3546 
    3647  void requestRouterShutdown();
  • launchers/macosx/RouterTask.mm

    reb81cada r3c0a8cf  
    113113#ifdef __cplusplus
    114114
    115 
    116 const std::vector<NSString*> JavaRunner::defaultStartupFlags {
    117     @"-Xmx512M",
    118     @"-Xms128m",
    119     @"-Djava.awt.headless=true",
    120     @"-Dwrapper.logfile=/tmp/router.log",
    121     @"-Dwrapper.logfile.loglevel=DEBUG",
    122     @"-Dwrapper.java.pidfile=/tmp/routerjvm.pid",
    123     @"-Dwrapper.console.loglevel=DEBUG"
    124 };
    125 
    126 const std::vector<std::string> JavaRunner::defaultFlagsForExtractorJob {
    127     "-Xmx512M",
    128     "-Xms128m",
    129     "-Djava.awt.headless=true"
    130 };
    131 
    132115JavaRunner::JavaRunner(std::string& javaBin, std::string& arguments, std::string& i2pBaseDir, const fp_proc_t& execFn, const fp_t& cb)
    133116  : javaBinaryPath(javaBin), javaRouterArgs(arguments), _i2pBaseDir(i2pBaseDir), executingFn(execFn), exitCallbackFn(cb)
  • launchers/macosx/include/strutil.hpp

    reb81cada r3c0a8cf  
    9999}
    100100
    101 #ifdef CPP17
     101#if __cplusplus > 201402L
    102102
    103103
    104 using std::experimental::optional;
     104using std::optional;
    105105
    106106// Use CFStringRef instead of NSString*, otherwise disable ARC
  • launchers/macosx/main.mm

    reb81cada r3c0a8cf  
    3434#include "include/fn.h"
    3535#include "include/portcheck.h"
     36#import "SBridge.h"
    3637
    3738#ifdef __cplusplus
    38 #import "SBridge.h"
     39#include <string>
    3940
    4041#include "include/subprocess.hpp"
     
    4344using namespace subprocess;
    4445
    45 JvmListSharedPtr gRawJvmList = nullptr;
    46 
    47 maybeAnRouterRunner getGlobalRouterObject()
    48 {
    49   std::lock_guard<std::mutex> lock(globalRouterStatusMutex);
    50   return globalRouterStatus; // Remember this might be nullptr now.
    51 }
    52 
    53 void setGlobalRouterObject(I2PRouterTask* newRouter)
    54 {
    55   std::lock_guard<std::mutex> lock(globalRouterStatusMutex);
    56   globalRouterStatus = newRouter;
    57 }
    58 
    59 
    60 pthread_mutex_t mutex;
    61 
    62 bool getGlobalRouterIsRunning()
    63 {
    64   pthread_mutex_lock(&mutex);
    65   bool current = isRuterRunning;
    66   pthread_mutex_unlock(&mutex);
    67   return current;
    68 }
    69 void setGlobalRouterIsRunning(bool running)
    70 {
    71   pthread_mutex_lock(&mutex);
    72   isRuterRunning = running;
    73   pthread_mutex_unlock(&mutex);
    74 }
    75 
    7646#endif
    7747
     
    8959
    9060- (void) awakeFromNib {
     61}
     62
     63
     64- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center
     65     shouldPresentNotification:(NSUserNotification *)notification {
     66  return YES;
    9167}
    9268
     
    126102      mkdir(basePath.c_str(), S_IRUSR | S_IWUSR | S_IXUSR);
    127103
    128       auto cli = JavaRunner::defaultFlagsForExtractorJob;
     104      auto cli = defaultFlagsForExtractorJob;
    129105      setenv("I2PBASE", basePath.c_str(), true);
    130106      setenv("ZIPPATH", zippath.c_str(), true);
     
    144120      NSURL *baseURL = [NSURL fileURLWithPath:newString];
    145121     
    146       NSLog(@"MEEH URL PATH: %s", [baseURL fileSystemRepresentation]);
    147 
    148       auto charCli = map(cli, [](std::string str){ return str.c_str(); });
    149122      std::string execStr = std::string([rs.getJavaHome UTF8String]);
    150       // TODO: Cheap hack, make it better.
    151       replace(execStr, "Internet Plug-Ins", "Internet\\ Plug-Ins");
    152       replace(execStr, "\n", "");
    153       NSLog(@"Java path1 = %s", execStr.c_str());
    154       [rs setJavaHome: [NSString stringWithFormat:@"%s", execStr.c_str()]];
    155123      for_each(cli, [&execStr](std::string str){ execStr += std::string(" ") + str; });
    156      
    157       //execStr = replace(execStr, "\\\\ ", "\\ ");
    158       //NSLog(@"Java path2 = %s", execStr.c_str());
    159124
    160125      NSLog(@"Trying cmd: %@", [NSString stringWithUTF8String:execStr.c_str()]);
     
    198163}
    199164
    200 #endif
    201 
    202 - (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center
    203                                shouldPresentNotification:(NSUserNotification *)notification {
    204     return YES;
    205 }
    206 
    207 
    208 #ifdef __cplusplus
    209165
    210166- (NSString *)userSelectJavaHome:(JvmListPtr)rawJvmList
     
    228184}
    229185
    230 
    231 - (void)userChooseJavaHome {
    232   listAllJavaInstallsAvailable();
    233   std::shared_ptr<JvmHomeContext> appContext = std::shared_ptr<JvmHomeContext>( new JvmHomeContext() );
    234   for (auto item : *appContext->getJvmList()) {
    235     printf("JVM %s (Version: %s, Directory: %s)\n", item->JVMName.c_str(), item->JVMPlatformVersion.c_str(), item->JVMHomePath.c_str());
    236   }
    237   JvmListPtr rawJvmList = appContext->getJvmList();
    238   NSString * userJavaHome = [self userSelectJavaHome: rawJvmList];
    239   // TODO: Add logic so user can set preferred JVM
    240 }
    241 
    242 #endif
    243 
    244186- (void)setApplicationDefaultPreferences {
    245187  auto defaultJVMHome = check_output({"/usr/libexec/java_home","-v",DEF_MIN_JVM_VER});
     
    247189  trim(tmpStdStr);
    248190  auto cfDefaultHome  = CFStringCreateWithCString(NULL, const_cast<const char *>(tmpStdStr.c_str()), kCFStringEncodingUTF8);
    249   /*[self.userPreferences registerDefaults:@{
     191  [self.userPreferences registerDefaults:@{
    250192    @"javaHome" : (NSString *)cfDefaultHome,
    251193    @"lastI2PVersion" : (NSString *)CFSTR(DEF_I2P_VERSION),
     
    254196    @"autoStartRouter": @YES,
    255197    @"i2pBaseDirectory": (NSString *)CFStringCreateWithCString(NULL, const_cast<const char *>(getDefaultBaseDir().c_str()), kCFStringEncodingUTF8)
    256   }];*/
     198  }];
    257199  if (self.enableVerboseLogging) NSLog(@"Default JVM home preference set to: %@", cfDefaultHome);
    258200
     
    264206
    265207  if (self.enableVerboseLogging) NSLog(@"Default preferences stored!");
    266 }
     208#endif
     209}
     210
     211
    267212
    268213
     
    272217  self.swiftRuntime = [[SwiftMainDelegate alloc] init];
    273218 
     219  // This setup allows the application to send notifications
    274220  [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
     221 
     222 
    275223  // Start with user preferences
    276224  self.userPreferences = [NSUserDefaults standardUserDefaults];
     
    278226  self.enableLogging = [self.userPreferences boolForKey:@"enableLogging"];
    279227  self.enableVerboseLogging = [self.userPreferences boolForKey:@"enableVerboseLogging"];
    280 
    281 
    282 #ifdef __cplusplus
    283   gRawJvmList = std::make_shared<std::list<JvmVersionPtr> >(std::list<JvmVersionPtr>());
    284 #endif
    285228  // In case we are unbundled, make us a proper UI application
    286229  [NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];
    287230  [NSApp activateIgnoringOtherApps:YES];
    288231
    289   // TODO: Also check for new installations from time to time.
    290  
     232
    291233#ifdef __cplusplus
    292   auto javaHomePref = [self.userPreferences stringForKey:@"javaHome"];
    293   if (self.enableVerboseLogging)
    294   {
    295     NSLog(@"Java home from preferences: %@", javaHomePref);
    296   }
    297 
    298   if (self.enableVerboseLogging)
    299   {
    300     NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
    301     NSLog(@"Appdomain is: %@", appDomain);
    302   }
    303 
    304   NSLog(@"We should have started the statusbar object by now...");
     234  //gRawJvmList = std::make_shared<std::list<JvmVersionPtr> >(std::list<JvmVersionPtr>());
     235
    305236  RouterProcessStatus* routerStatus = [[RouterProcessStatus alloc] init];
    306 
    307237  std::string i2pBaseDir(getDefaultBaseDir());
    308 
    309   auto pref = self.userPreferences;
    310  
     238  NSLog(@"i2pBaseDir = %s", i2pBaseDir.c_str());
    311239  bool shouldAutoStartRouter = false;
    312 
     240 
     241  // TODO: Make the port a setting which defaults to 7657
    313242  if (port_check(7657) != 0)
    314243  {
     
    325254  if (self.enableVerboseLogging) NSLog(@"processinfo %@", [[NSProcessInfo processInfo] arguments]);
    326255
    327   auto getJavaBin = [&pref,&self]() -> std::string {
    328     // Get Java home
    329     /*NSString* val = @"";
    330     val = [pref stringForKey:@"javaHome"];
    331     if (val == NULL) val = @"";
    332     if (self.enableVerboseLogging) NSLog(@"Javahome: %@", val);
    333     auto javaHome = std::string([val UTF8String]);
    334     //trim(javaHome); // Trim to remove endline
    335     auto javaBin = std::string(javaHome);
    336     javaBin += "/bin/java"; // Append java binary to path.
    337     return javaBin;*/
    338     DetectJava *dt = [[DetectJava alloc] init];
    339     [dt findIt];
    340     if ([dt isJavaFound]) {
    341       return [dt.javaHome UTF8String];
    342     } else {
    343       throw new std::runtime_error("Java home fatal error");
    344     }
    345   };
    346 
    347256
    348257  NSBundle *launcherBundle = [NSBundle mainBundle];
    349258 
    350   auto jarResPath = [launcherBundle pathForResource:@"launcher" ofType:@"jar"];
    351   NSLog(@"Trying to load launcher.jar from url = %@", jarResPath);
    352    
     259  // Helper object to hold statefull path information
    353260  self.metaInfo = [[ExtractMetaInfo alloc] init];
    354   //self.metaInfo.i2pBase = [NSString stringWithUTF8String:i2pBaseDir.c_str()];
    355   self.metaInfo.javaBinary = [NSString stringWithUTF8String:getJavaBin().c_str()];
     261  self.metaInfo.i2pBase = [NSString stringWithUTF8String:i2pBaseDir.c_str()];
     262  self.metaInfo.javaBinary = [routerStatus getJavaHome];
    356263  self.metaInfo.jarFile = [launcherBundle pathForResource:@"launcher" ofType:@"jar"];
    357264  self.metaInfo.zipFile = [launcherBundle pathForResource:@"base" ofType:@"zip"];
    358265
    359266  std::string basearg("-Di2p.dir.base=");
    360   //basearg += i2pBaseDir;
     267  basearg += i2pBaseDir;
    361268
    362269  std::string jarfile("-cp ");
    363270  jarfile += [self.metaInfo.zipFile UTF8String];
    364271 
     272  auto sBridge = [[SBridge alloc] init];
     273 
     274  // Initialize the Swift environment (the UI components)
     275  [self.swiftRuntime applicationDidFinishLaunching];
    365276
    366277  struct stat sb;
     
    370281    if (self.enableVerboseLogging) NSLog(@"I2P Directory don't exists!");
    371282
     283    // Might be hard to read if you're not used to Objective-C
     284    // But this is a "function call" that contains a "callback function"
    372285    [self extractI2PBaseDir:^(BOOL success, NSError *error) {
    373286      sendUserNotification(@"I2P is done extracting", @"I2P is now installed and ready to run!");
    374       [self.swiftRuntime applicationDidFinishLaunching];
    375287      NSLog(@"Done extracting I2P");
    376       if (shouldAutoStartRouter) [self startupI2PRouter];
     288     
     289      if (shouldAutoStartRouter) {
     290        [sBridge startupI2PRouter:self.metaInfo.i2pBase javaBinPath:self.metaInfo.javaBinary];
     291        [routerStatus setRouterRanByUs: true];
     292      }
    377293    }];
    378294
    379295  } else {
    380     if (self.enableVerboseLogging) NSLog(@"I2P directory found!");
    381     if (shouldAutoStartRouter) [self startupI2PRouter];
    382     [self.swiftRuntime applicationDidFinishLaunching];
     296    // I2P was already found extracted
     297   
     298    if (shouldAutoStartRouter) {
     299      [sBridge startupI2PRouter:self.metaInfo.i2pBase javaBinPath:self.metaInfo.javaBinary];
     300      [routerStatus setRouterRanByUs: true];
     301    }
    383302  }
    384303 
     
    412331{
    413332  NSApplication *app = [NSApplication sharedApplication];
    414   //NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    415333
    416334  AppDelegate *appDelegate = [[AppDelegate alloc] initWithArgc:argc argv:argv];
    417335  app.delegate = appDelegate;
     336  auto mainBundle = [NSBundle mainBundle];
     337  NSString* stringNameBundle = [mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey];
     338  if ([[NSRunningApplication runningApplicationsWithBundleIdentifier:[mainBundle bundleIdentifier]] count] > 1) {
     339    [[NSAlert alertWithMessageText:[NSString stringWithFormat:@"Another copy of %@ is already running.",stringNameBundle]
     340                     defaultButton:nil alternateButton:nil otherButton:nil informativeTextWithFormat:@"This copy will now quit."] runModal];
     341   
     342    [NSApp terminate:nil];
     343  }
    418344  [NSBundle loadNibNamed:@"I2Launcher" owner:NSApp];
    419345
    420346  [NSApp run];
    421   // Handle any errors
    422   //[pool drain];
    423347  return 0;
    424348}
Note: See TracChangeset for help on using the changeset viewer.